leetcode339. 嵌套列表权重和
生活随笔
收集整理的這篇文章主要介紹了
leetcode339. 嵌套列表权重和
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
給定一個(gè)嵌套的整數(shù)列表,請(qǐng)返回該列表按深度加權(quán)后所有整數(shù)的總和。
每個(gè)元素要么是整數(shù),要么是列表。同時(shí),列表中元素同樣也可以是整數(shù)或者是另一個(gè)列表。
示例 1:
輸入: [[1,1],2,[1,1]]
輸出: 10?
解釋: 因?yàn)榱斜碇杏兴膫€(gè)深度為 2 的 1 ,和一個(gè)深度為 1 的 2。
示例 2:
輸入: [1,[4,[6]]]
輸出: 27?
解釋: 一個(gè)深度為 1 的 1,一個(gè)深度為 2 的 4,一個(gè)深度為 3 的 6。所以,1 + 4*2 + 6*3 = 27。
思路:其實(shí)時(shí)間主要浪費(fèi)在讀題上了,不知道這個(gè)NestedInteger怎么用,是個(gè)啥東西。
就是最簡(jiǎn)單的搜索。
/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* public interface NestedInteger {* // Constructor initializes an empty nested list.* public NestedInteger();** // Constructor initializes a single integer.* public NestedInteger(int value);** // @return true if this NestedInteger holds a single integer, rather than a nested list.* public boolean isInteger();** // @return the single integer that this NestedInteger holds, if it holds a single integer* // Return null if this NestedInteger holds a nested list* public Integer getInteger();** // Set this NestedInteger to hold a single integer.* public void setInteger(int value);** // Set this NestedInteger to hold a nested list and adds a nested integer to it.* public void add(NestedInteger ni);** // @return the nested list that this NestedInteger holds, if it holds a nested list* // Return null if this NestedInteger holds a single integer* public List<NestedInteger> getList();* }*/ class Solution {public int depthSum(List<NestedInteger> nestedList) {return depthSum(nestedList, 1);}public int depthSum(List<NestedInteger> list, int depth) {int sum = 0;for (NestedInteger n : list) {if (n.isInteger()) sum += n.getInteger() * depth;else sum += depthSum(n.getList(), depth + 1);}return sum; } }?
總結(jié)
以上是生活随笔為你收集整理的leetcode339. 嵌套列表权重和的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: leetcode236 二叉树的最近公共
- 下一篇: 大数加减乘