当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
随机推荐
Pigsty:开箱即用的开源数据库发行版
数学基础(五)最优化理论(最优化,无约束,有约束,拉格朗日乘子的意义,KKT条件)
直播预告|从新手村到魔王城,高效默契的敏捷团队如何炼成
一文带你拿下信号卷积—常见信号卷积
HTTP学习——协议与术语、HTTP、缓存、Cookie
Lua--table操作
v-model指令:获取和设置表单元素的值
leetcode:1137. 第 N 个泰波那契数
超宽带uwb精准定位,厘米级室内定位技术,实时高精度方案应用
山西:一煤矿发生死亡1人安全事故 被责令停产整顿
视频转成gif动图怎么操作?仅需三步在线完成视频转gif
重庆新壹汽与一汽集团达成新能源项目战略合作,赋能“碳中和”创造“碳财富”
Polling and the principle of webSocket and socket.io
【科研】常见火灾数据集
常用持续集成工具对比
bp神经网络反向传播原理,BP神经网络反向传播
注解和反射、持续
被大厂面试官参考的Redis笔记,堪称Redis面试天花板
How to generate code using the Swift Package plugin
Mastodon:可创建类似推特的开源社交网络服务器