lifeiteng

339. Nested List Weight Sum

Sep 25th, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.54 KB | None | 0 0
  1. /**
  2.  * // This is the interface that allows for creating nested lists.
  3.  * // You should not implement it, or speculate about its implementation
  4.  * public interface NestedInteger {
  5.  *     // Constructor initializes an empty nested list.
  6.  *     public NestedInteger();
  7.  *
  8.  *     // Constructor initializes a single integer.
  9.  *     public NestedInteger(int value);
  10.  *
  11.  *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
  12.  *     public boolean isInteger();
  13.  *
  14.  *     // @return the single integer that this NestedInteger holds, if it holds a single integer
  15.  *     // Return null if this NestedInteger holds a nested list
  16.  *     public Integer getInteger();
  17.  *
  18.  *     // Set this NestedInteger to hold a single integer.
  19.  *     public void setInteger(int value);
  20.  *
  21.  *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
  22.  *     public void add(NestedInteger ni);
  23.  *
  24.  *     // @return the nested list that this NestedInteger holds, if it holds a nested list
  25.  *     // Return null if this NestedInteger holds a single integer
  26.  *     public List<NestedInteger> getList();
  27.  * }
  28.  */
  29. class Solution {
  30.     public int depthSum(List<NestedInteger> nestedList) {
  31.         return dfs(nestedList, 1);
  32.     }
  33.    
  34.     int dfs(List<NestedInteger> list, int w)
  35.     {
  36.         int res = 0;
  37.         for(NestedInteger k : list)
  38.         {
  39.             if(k.isInteger()) res += w * k.getInteger();
  40.             else res += dfs(k.getList(), w + 1);
  41.         }
  42.         return res;
  43.     }
  44. }
Add Comment
Please, Sign In to add comment