lifeiteng

364. Nested List Weight Sum II

Sep 25th, 2018
53
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.83 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 depthSumInverse(List<NestedInteger> nestedList) {
  31.         int d = depth(nestedList);
  32.         return dfs(nestedList, d);
  33.     }
  34.    
  35.     int depth(List<NestedInteger> list)
  36.     {
  37.         int res = 1;
  38.         for(NestedInteger k : list)
  39.         {
  40.             if(k.isInteger()) continue;
  41.             res = Math.max(res, 1 + depth(k.getList()));
  42.         }
  43.         return res;
  44.     }
  45.  
  46.     int dfs(List<NestedInteger> list, int w)
  47.     {
  48.         int res = 0;
  49.         for(NestedInteger k : list)
  50.         {
  51.             if(k.isInteger()) res += w * k.getInteger();
  52.             else res += dfs(k.getList(), w - 1);
  53.         }
  54.         return res;
  55.     }
  56. }
Add Comment
Please, Sign In to add comment