当前位置:网站首页>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;
}
};
边栏推荐
- cube-studio配置镜像仓库并允许
- 一文带你彻底拿下a,b两点间等效电阻
- nacos服务注册
- matsuri.icu 筛选单场直播中 指定用户的弹幕
- Gif动图怎么用视频做?一键在线完成视频转gif制作
- FTXUI按键和ROS2 CLI组合使用笔记(turtlesim+teleop)
- 数学基础(五)最优化理论(最优化,无约束,有约束,拉格朗日乘子的意义,KKT条件)
- The sword refers to OfferⅡ 045. The bottommost leftmost value of the binary tree dfs
- ahx文件转mav文件 工具分享及说明
- 【荣耀智慧服务】快捷服务开发指南
猜你喜欢
随机推荐
shell获取前n天的日期
注解和反射、持续
超宽带uwb精准定位,厘米级室内定位技术,实时高精度方案应用
v-if指令:操作dom元素(标签)的显示与隐藏
MS | 使用小技巧不完全总结
直播预告|从新手村到魔王城,高效默契的敏捷团队如何炼成
年薪60万+?这份10万字的面试突击宝典涵盖阿里 P5 工程师~P7 所有技术栈
接口测试中,应不应该用数据库
C:枚举的优缺
Alluxio on Amazon EMR 集成实践
如何修改gif图片尺寸?教你一键裁剪gif尺寸
promise笔记(三)
pytorch 模型GPU推理时间探讨3——正确计算模型推理时间
华为-坐标移动
自助服务知识库是什么?
Could NOT find Doxygen (missing: DOXYGEN_EXECUTABLE)
Gif动图如何快速制作?教你1分钟图片合成gif的方法
在Istio中,到底怎么获取 Envoy 访问日志?
如何将jpg图片变成gif?教你一分钟图片合成gif的方法
不爱生活的段子手不是好设计师|ONES 人物