// This is the interface that allows for creating nested lists. // You should not implement it, or speculate about its implementation publicinterfaceNestedInteger {
// @return true if this NestedInteger holds a single integer, // rather than a nested list. publicbooleanisInteger();
// @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(); }
递归版本:
1 2 3 4 5 6 7 8 9 10 11 12 13
public List<Integer> flatten1(List<NestedInteger> nestedList) { List<Integer> result = newArrayList<>(); for (inti=0; i < nestedList.size(); i++) { //是整数则添加到结果集 if (nestedList.get(i).isInteger()) { result.add(nestedList.get(i).getInteger()); continue; } //是列表则递归调用将结果全添加到结果集中 result.addAll(flatten1(nestedList.get(i).getList())); } return result; }