My code:
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @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();
*
* // @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();
* }
*/
public class Solution {
private int ret = 0;
public int depthSum(List<NestedInteger> nestedList) {
helper(nestedList, 1);
return ret;
}
private void helper(List<NestedInteger> nestedList, int depth) {
if (nestedList.size() == 0) {
return;
}
int sum = 0;
List<NestedInteger> next = new ArrayList<NestedInteger>();
for (int i = 0; i < nestedList.size(); i++) {
NestedInteger temp = nestedList.get(i);
if (temp.isInteger()) {
sum += temp.getInteger();
}
else {
for (NestedInteger curr : temp.getList()) {
next.add(curr);
}
}
}
ret += depth * sum;
helper(next, depth + 1);
}
}
看了下我的代码,发现其实是 BFS的思想。
先把每一层的integer 加起来,然后把list加入到一个新的list里面,然后走下一轮递归。
然后看了答案,发现有 DFS的解法。
My code:
/**
* // This is the interface that allows for creating nested lists.
* // You should not implement it, or speculate about its implementation
* public interface NestedInteger {
*
* // @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();
*
* // @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();
* }
*/
public class Solution {
public int depthSum(List<NestedInteger> nestedList) {
return helper(nestedList, 1);
}
private int helper(List<NestedInteger> nestedList, int depth) {
int sum = 0;
for (NestedInteger temp : nestedList) {
if (temp.isInteger()) {
sum += depth * temp.getInteger();
}
else {
sum += helper(temp.getList(), depth + 1);
}
}
return sum;
}
}
reference:
https://leetcode.com/articles/nested-list-weight-sum/
Anyway, Good luck, Richardo! — 09/10/2016