[LeetCode] 339 Nested List Weight Sum 嵌套链表权重和

来源:互联网 发布:编写流程图的软件 编辑:程序博客网 时间:2024/06/03 18:38

[LeetCode] Nested List Weight Sum 嵌套链表权重和

Given a nested list of integers, return the sum of all integers in the list weighted by their depth.

Each element is either an integer, or a list – whose elements may also be integers or other lists.

Example 1: Given the list [[1,1],2,[1,1]], return 10. (four 1’s at
depth 2, one 2 at depth 1)

Example 2: Given the list [1,[4,[6]]], return 27. (one 1 at depth 1,
one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27)

思路:
1. 嵌套的数据结构是有层次的,用stack就可以一层一层的解开嵌套,或者用recursive的方法: 如果有层级的明显标志,例如(,[等,可以用stack,本题还是用recursive的方法来解开这个数据结构;
2. 利用nestedInteger的方法,isInteger(), getInteger(), getList()

int depthSum(vector<NestedInteger>& nestedList) {    return helper(ni,0);}int helper(vector<NestedInteger>& nestedList, int depth){    int res=0;    for(auto&k:nestedList){        res+=k.isInteger?k.getInteger()*depth:helper(k.getList(),depth+1);    }    return res;}
0 0
原创粉丝点击