高级农民
- 积分
- 1216
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2017-8-24
- 最后登录
- 1970-1-1
|
注册一亩三分地论坛,查看更多干货!
您需要 登录 才可以下载或查看附件。没有帐号?注册账号 
x
大家好,这道题不好debug,因为好多写好的api
有一件事不明,就是如果输入是[[1,1],2,[ ]]的时候,这个递归的程序怎样处理空list的?返回的是null吗?
进而,这个recursion的base case是什么? 貌似不像是树那样if(root==null) return 逻辑:
- /**
- * // 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);
- *
- * // [url=home.php?mod=space&uid=160137]@return[/url] 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) {
- if(nestedList == null) return 0;
- return helper(nestedList,1);
- }
- public int helper(List<NestedInteger> nestedList, int level){
- int sum=0;
- for(NestedInteger nest: nestedList){
- if(nest.isInteger()){
- sum+=nest.getInteger() * level;
- }else{
- sum+= helper(nest.getList(),level+1);//所以这个recursion没有base case吗
- }
- }
- return sum;
- }
- }
复制代码
求教,谢谢
|
上一篇: 求问关于最短路径树和最小生成树的边权值比较下一篇: 一道关于MST树的算法设计题
|