当前位置:网站首页>leetcode:339 嵌套列表权重和
leetcode:339 嵌套列表权重和
2022-08-10 16:39:00 【OceanStar的学习笔记】
题目来源
题目描述
给定一个嵌套的整数列表,请返回该列表按深度加权后所有整数的总和。
每个元素要么是整数,要么是列表。同时,列表中元素同样也可以是整数或者是另一个列表。
示例 1:
输入: [[1,1],2,[1,1]]
输出: 10
解释: 因为列表中有四个深度为 2 的 1 ,和一个深度为 1 的 2。
示例 2:
输入: [1,[4,[6]]]
输出: 27
解释: 一个深度为 1 的 1,一个深度为 2 的 4,一个深度为 3 的 6。所以,1 + 42 + 63 = 27。
// This is the interface that allows for creating nested lists.
// You should not implement it, or speculate about its implementation
class NestedInteger {
public:
// Constructor initializes an empty nested list.
NestedInteger();
// Constructor initializes a single integer.
NestedInteger(int value);
// Return true if this NestedInteger holds a single integer, rather than a nested list.
bool isInteger() const;
// Return the single integer that this NestedInteger holds, if it holds a single integer
// The result is undefined if this NestedInteger holds a nested list
int getInteger() const;
// Set this NestedInteger to hold a single integer.
void setInteger(int value);
// Set this NestedInteger to hold a nested list and adds a nested integer to it.
void add(const NestedInteger &ni);
// Return the nested list that this NestedInteger holds, if it holds a nested list
// The result is undefined if this NestedInteger holds a single integer
const vector<NestedInteger> &getList() const;
};
class Solution {
public:
int depthSum(vector<NestedInteger>& nestedList) {
}
};
题目解析
实现一
class Solution {
int process(NestedInteger ni, int depth){
if(ni.isInteger()){
return depth* ni.getInteger();
}
int ans = 0;
for(auto a : ni.getList()){
ans += process(a, depth + 1);
}
return ans;
}
public:
int depthSum(vector<NestedInteger>& nestedList) {
int ans = 0;
for(auto a : nestedList){
ans += process(a, 1);
}
return ans;
}
};
实现二
class Solution {
public:
int depthSum(vector<NestedInteger>& nestedList) {
return helper(nestedList, 1);
}
int helper(vector<NestedInteger>& nl, int depth) {
int res = 0;
for (auto a : nl) {
res += a.isInteger() ? a.getInteger() * depth : helper(a.getList(), depth + 1);
}
return res;
}
};
边栏推荐
猜你喜欢
随机推荐
神经网络有哪些激活函数,卷积神经网络有哪些
剑指OfferⅡ 045.二叉树最底层最左边的值 dfs
C专家编程 第10章 再论指针 10.5 使用指针向函数传递一个多维数组
App自动化测试框架设计与实现
华为-求int型正整数在内存中存储时1的个数
Basic knowledge of software engineering--requirements analysis
requests库访问接口
华为-坐标移动
注解和反射、持续
李斌带不动的长安新能源高端梦,华为和“宁王”能救吗?
cube-studio配置镜像仓库并允许
分享几个自动化测试的练手项目
pytorch 模型GPU推理时间探讨3——正确计算模型推理时间
Polling and the principle of webSocket and socket.io
v-bind指令:设置元素的属性
雷达存在感应器技术,实时感知控制应用,雷达人体探测方案
从抖音到火山引擎——看流媒体技术演进和机会
超宽带uwb精准定位,厘米级室内定位技术,实时高精度方案应用
Pytorch GPU模型推理时间探讨
PNG如何变gif?教你一招png秒变gif动图的方法