給定一個嵌套的整數列表,請返回該列表按深度加權后所有整數的總和。
每個元素要么是整數,要么是列表。同時,列表中元素同樣也可以是整數或者是另一個列表。
示例 1:
輸入: [[1,1],2,[1,1]]
輸出: 10?
解釋: 因為列表中有四個深度為 2 的 1 ,和一個深度為 1 的 2。
示例 2:
輸入: [1,[4,[6]]]
輸出: 27?
解釋: 一個深度為 1 的 1,一個深度為 2 的 4,一個深度為 3 的 6。所以,1 + 4*2 + 6*3 = 27。
思路:其實時間主要浪費在讀題上了,不知道這個NestedInteger怎么用,是個啥東西。
就是最簡單的搜索。
/*** // 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;
}
}
?