[LeetCode] 339 Nested List Weight Sum 嵌套链表权重和
2017-01-04 08:59
330 查看
[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()
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; }
相关文章推荐
- [LeetCode] Nested List Weight Sum 嵌套链表权重和
- [LeetCode] Nested List Weight Sum II 嵌套链表权重和之二
- LeetCode 364. Nested List Weight Sum II 嵌套链表权重和之二
- Leetcode 339 Nested List Weight Sum
- Leetcode-Algorithms Nested List Weight Sum
- Leetcode: Nested List Weight Sum II
- 339. Nested List Weight Sum
- 339. Nested List Weight Sum
- 339. Nested List Weight Sum
- LeetCod 339.Nested List Weight Sum
- Leetcode: Nested List Weight Sum
- Leetcode 364 Nested List Weight Sum II
- Leetcode Nested List Weight Sum
- Leetcode: Nested List Weight Sum
- LeetCode Nested List Weight Sum
- LeetCode Nested List Weight Sum II
- LeetCode "Nested List Weight Sum"
- Nested List Weight Sum
- Nested List Weight Sum II
- Nested List Weight Sum II