当前位置:网站首页>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;
}
};
边栏推荐
猜你喜欢
随机推荐
观测云入选 CNCF 云原生全景图
document.title获取当前网页的标题
【QT VS项目名称修改】
分类常用的神经网络模型,深度神经网络主要模型
Annual salary of 600,000+?This 100,000-word interview assault book covers all technology stacks from Ali P5 engineers to P7
险资又做LP,一出手40亿
【荣耀智慧服务】快捷服务开发指南
视频转gif怎样操作?1分钟在线视频转gif制作
聚焦企业流程智能化发展新趋势,中国信通院2022 RPA创新产业峰会即将开启
FTXUI基础笔记(botton按钮组件进阶)
x86 与 x64 架构下函数参数传递的区别【汇编语言】
C专家编程 第10章 再论指针 10.6 使用指针从函数返回一个数组
app自动化测试webview怎么操作
How to realize full backup and incremental backup of MySQL database
直播预告|从新手村到魔王城,高效默契的敏捷团队如何炼成
雷达存在感应器技术,实时感知控制应用,雷达人体探测方案
找到一个超级神奇,百试百灵的解决 ModuleNotFoundError: No module named xxx 的方法
不爱生活的段子手不是好设计师|ONES 人物
FTXUI基础笔记(hello world)
神经网络全连接层的作用,各种神经网络的优缺点









