LeetCode 364 - Nested List Weight Sum II


Related: LeetCode 339 - Nested List Weight Sum
http://blog.csdn.net/qq508618087/article/details/51743408
Given a nested list of integers, return the sum of all integers in the list weighted by their depth.
Each element is either an integer, or a list -- whose elements may also be integers or other lists.
Different from the previous question where weight is increasing from root to leaf, now the weight is defined from bottom up. i.e., the leaf level integers have weight 1, and the root level integers have the largest weight.
Example 1:
Given the list [[1,1],2,[1,1]], return 8. (four 1's at depth 1, one 2 at depth 2)
Example 2:
Given the list [1,[4,[6]]], return 17. (one 1 at depth 3, one 4 at depth 2, and one 6 at depth 1; 1*3 + 4*2 + 6*1 = 17)
  1.  * public interface NestedInteger { 
  2.  * 
  3.  *     // @return true if this NestedInteger holds a single integer, rather than a nested list. 
  4.  *     public boolean isInteger(); 
  5.  * 
  6.  *     // @return the single integer that this NestedInteger holds, if it holds a single integer 
  7.  *     // Return null if this NestedInteger holds a nested list 
  8.  *     public Integer getInteger(); 
  9.  * 
  10.  *     // @return the nested list that this NestedInteger holds, if it holds a nested list 
  11.  *     // Return null if this NestedInteger holds a single integer 
  12.  *     public List<NestedInteger> getList(); 
  13.  * } 
X. BFS
https://discuss.leetcode.com/topic/49041/no-depth-variable-no-multiplication/
Inspired by lzb700m's solution and one of mine. Instead of multiplying by depth, add integers multiple times (by going level by level and adding the unweighted sum to the weighted sum after each level).
public int depthSumInverse(List<NestedInteger> nestedList) {
    int unweighted = 0, weighted = 0;
    while (!nestedList.isEmpty()) {
        List<NestedInteger> nextLevel = new ArrayList<>();
        for (NestedInteger ni : nestedList) {
            if (ni.isInteger())
                unweighted += ni.getInteger();
            else
                nextLevel.addAll(ni.getList());
        }
        weighted += unweighted;
        nestedList = nextLevel;
    }
    return weighted;
}
http://www.cnblogs.com/grandyang/p/5615583.html
下面这个方法就比较巧妙了,由史蒂芬大神提出来的,这个方法用了两个变量unweighted和weighted,非权重和跟权重和,初始化均为0,然后如果nestedList不为空开始循环,先声明一个空数组nextLevel,遍历nestedList中的元素,如果是数字,则非权重和加上这个数字,如果是数组,就加入nextLevel,这样遍历完成后,第一层的数字和保存在非权重和unweighted中了,其余元素都存入了nextLevel中,此时我们将unweighted加到weighted中,将nextLevel赋给nestedList,这样再进入下一层计算,由于上一层的值还在unweighted中,所以第二层计算完将unweighted加入weighted中时,相当于第一层的数字和被加了两次,这样就完美的符合要求了

    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int unweighted = 0, weighted = 0;
        while (!nestedList.empty()) {
            vector<NestedInteger> nextLevel;
            for (auto a : nestedList) {
                if (a.isInteger()) {
                    unweighted += a.getInteger();
                } else {
                    nextLevel.insert(nextLevel.end(), a.getList().begin(), a.getList().end());
                }
            }
            weighted += unweighted;
            nestedList = nextLevel;
        }
        return weighted;
    }
https://discuss.leetcode.com/topic/49023/share-my-2ms-intuitive-one-pass-no-multiplication-solution
The idea is to pass the current found integer sum into the next level of recursion, and return it back again. So that we don't have to count the number of levels in the nested list.
    public int depthSumInverse(List<NestedInteger> nestedList) {
        return helper(nestedList, 0);
    }
    
    private int helper(List<NestedInteger> niList, int prev) {
        int intSum = prev;
        List<NestedInteger> levelBreak = new ArrayList<>();
        
        for (NestedInteger ni : niList) {
            if (ni.isInteger()) {
                intSum += ni.getInteger();
            } else {
                levelBreak.addAll(ni.getList());
            }
        }
        
        int listSum = levelBreak.isEmpty()? 0 : helper(levelBreak, intSum);

        return listSum + intSum;
    }
X. DFS

https://segmentfault.com/a/1190000005937820
如果说第一道题的关键是记录层次,那么这一题的关键是把这一层的integer sum传到下一层去
public int DFS(List<NestedInteger> nestedList, int intSum) {
    //关键点在于把上一层的integer sum传到下一层去,这样的话,接下来还有几层,每一层都会加上这个integer sum,也就等于乘以了它的层数
    List<NestedInteger> nextLevel = new ArrayList<>();
    int listSum = 0;
    for (NestedInteger list : nestedList) {
        if (list.isInteger()) {
            intSum += list.getInteger();
        } else {
            nextLevel.addAll(list.getList());
        }
    }
    listSum = nextLevel.isEmpty() ? 0 : DFS(nextLevel, intSum);
    return listSum + intSum;
}

public int depthSumInverse(List<NestedInteger> nestedList) {
    return DFS(nestedList, 0);
}
思路: 和之前的一题不同在于这题结点的权值是越靠近根部越高, 而在叶子结点则越低. 所以在找到最大深度之前你是无法计算的, 也就是说我们可以将每个值和他的深度边搜索边存起来, 并且计算最大深度是多少. 最后将所有的点遍历完之后就得到了所有需要的信息. 这时就可以根据最大深度和每一个点的深度来计算加权值了.
    void DFS(vector<NestedInteger>& nestedList, int depth)
    {
        maxDepth = max(maxDepth, depth);
        for(auto val: nestedList)
        {
            if(!val.isInteger()) DFS(val.getList(), depth+1); 
            else nums.push_back(make_pair(val.getInteger(), depth));
        }
    }
    
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        if(nestedList.size() ==0) return 0;
        DFS(nestedList, 1);
        for(auto val: nums) result+= (maxDepth-val.second+1)*val.first;
        return result;
    }
private:
    vector<pair<int, int>> nums;
    int maxDepth = 0, result = 0;
方法:先检查最大深度,再计算。
    private int maxDepth(List<NestedInteger> nestedList, int depth) {
        int max = depth;
        for(NestedInteger ni : nestedList) {
            if (!ni.isInteger()) {
                max = Math.max(max, maxDepth(ni.getList(), depth + 1));
            }
        }
        return max;
    }
    private int sum(List<NestedInteger> nestedList, int depth) {
        int sum = 0;
        for(NestedInteger ni : nestedList) {
            if (ni.isInteger()) {
                sum += ni.getInteger() * depth;
            } else {
                sum += sum(ni.getList(), depth - 1);
            }
        }
        return sum;
    }
    public int depthSumInverse(List<NestedInteger> nestedList) {
        if (nestedList == null || nestedList.isEmpty()) return 0;
        int max = maxDepth(nestedList, 1);
        return sum(nestedList, max);
    }
X. BFS
http://www.cnblogs.com/grandyang/p/5615583.html
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int unweighted = 0, weighted = 0;
        queue<vector<NestedInteger>> q;
        q.push(nestedList);
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                vector<NestedInteger> t = q.front(); q.pop();
                for (auto a : t) {
                    if (a.isInteger()) unweighted += a.getInteger();
                    else if (!a.getList().empty()) q.push(a.getList());
                }
            }
            weighted += unweighted;
        }
        return weighted;
    }
https://discuss.leetcode.com/topic/49488/java-ac-bfs-solution
public int depthSumInverse(List<NestedInteger> nestedList) {
        if (nestedList == null) return 0;
        Queue<NestedInteger> queue = new LinkedList<NestedInteger>();
        int prev = 0;
        int total = 0;
        for (NestedInteger next: nestedList) {
            queue.offer(next);
        }
        
        while (!queue.isEmpty()) {
            int size = queue.size();
            int levelSum = 0;
            for (int i = 0; i < size; i++) {
                NestedInteger current = queue.poll();
                if (current.isInteger()) levelSum += current.getInteger();
                List<NestedInteger> nextList = current.getList();
                if (nextList != null) {
                    for (NestedInteger next: nextList) {
                        queue.offer(next);
                    }
                }
            }
            prev += levelSum;
            total += prev;
        }
        return total;
    }
What @dianhua1560 is trying to say is using prev in place of levelSum - updating prev with current level elements, and adding it to total at each level, allowing the previous elements to be added repeatedly at each level.
    while (!queue.isEmpty()) {
        int size = queue.size();
       // int levelSum = 0;
        for (int i = 0; i < size; i++) {
            NestedInteger current = queue.poll();
            if (current.isInteger()) prev += current.getInteger(); // <-- prev is not reset to 0
            List<NestedInteger> nextList = current.getList();
            if (nextList != null) {
                for (NestedInteger next: nextList) {
                    queue.offer(next);
                }
            }
        }
        //prev += levelSum;
        total += prev;
    }
http://www.cnblogs.com/grandyang/p/5615583.html
下面这种算法是常规的BFS解法,利用上面的建立两个变量unweighted和weighted的思路,大体上没什么区别:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int unweighted = 0, weighted = 0;
        queue<vector<NestedInteger>> q;
        q.push(nestedList);
        while (!q.empty()) {
            int size = q.size();
            for (int i = 0; i < size; ++i) {
                vector<NestedInteger> t = q.front(); q.pop();
                for (auto a : t) {
                    if (a.isInteger()) unweighted += a.getInteger();
                    else q.push(a.getList());
                }
            }
            weighted += unweighted;
        }
        return weighted;
    }
https://discuss.leetcode.com/topic/49008/java-easy-to-understand-solution
http://fangde2.blogspot.com/2016/07/leetcode-q364-nested-list-weight-sum-ii.html
public class Solution {
    Map<Integer, Integer> map = new HashMap<>();
    
    public int depthSumInverse(List<NestedInteger> nestedList) {
        int ret = 0;
        
        //use dfs to travese the List and put (depth, number) to the map
        dfs(nestedList, 1);
        
        int maxDepth = Integer.MIN_VALUE;
        
        //get the max depth
        for (int n : map.keySet()) {
            if (n>maxDepth)
                maxDepth = n;
        }
        
        //get the sum
        for (int n : map.keySet()) {
            ret += (maxDepth-n+1)*map.get(n);
        }
        
        return ret;
    }
    
    void dfs(List<NestedInteger> nestedList, int depth) {
        
        for (NestedInteger item : nestedList) {
            if (item.isInteger()) {
                Integer num = map.get(depth);
                if (num == null) {
                    map.put(depth, item.getInteger());
                }
                else {
                    map.put(depth, map.get(depth) + item.getInteger());
                }
            }
            else {
                dfs(item.getList(), depth+1);
            }
        }
    }
}
X.
https://discuss.leetcode.com/topic/49017/java-two-pass-dfs-solution
http://blog.csdn.net/jmspan/article/details/51747784
Java Two Pass DFS solution
    public int depthSumInverse(List<NestedInteger> nestedList) {
        if(nestedList == null || nestedList.size() == 0) return 0;
        int h = helper(nestedList);
        int res = getSum(nestedList, h);
        return res;
    }
    private int getSum(List<NestedInteger> l, int layer) {
        int sum = 0;
        if(l == null || l.size() == 0) return sum;
        for(NestedInteger n : l) {
            if(n.isInteger()) sum += n.getInteger() * layer;
            else sum += getSum(n.getList(), layer - 1);
        }
        return sum;
    }
    private int helper(List<NestedInteger> l) {
        if(l == null || l.size() == 0) return 0;
        int max = 0;
        for(NestedInteger n : l) {
            if(n.isInteger()) max = Math.max(max, 1);
            else max = Math.max(max, helper(n.getList()) + 1);
        }
        return max;
    }
X. Using stack
http://www.programcreek.com/2014/08/leetcode-nested-list-weight-sum-ii-java/

我最开始的想法是在遍历的过程中建立一个二维数组,把每层的数字都保存起来,然后最后知道了depth后,再来计算权重和,比如题目中给的两个例子,建立的二维数组分别为:
[[1,1],2,[1,1]]:
1 1 1 1
2
[1,[4,[6]]]:
1
4
6
这样我们就能算出权重和了
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int res = 0;
        vector<vector<int>> v;
        for (auto a : nestedList) {
            helper(a, 0, v);
        }
        for (int i = v.size() - 1; i >= 0; --i) {
            for (int j = 0; j < v[i].size(); ++j) {
                res += v[i][j] * (v.size() - i);
            }
        }
        return res;
    }
    void helper(NestedInteger &ni, int depth, vector<vector<int>> &v) {
        vector<int> t;
        if (depth < v.size()) t = v[depth];
        else v.push_back(t);
        if (ni.isInteger()) {
            t.push_back(ni.getInteger());
            if (depth < v.size()) v[depth] = t;
            else v.push_back(t);
        } else {
            for (auto a : ni.getList()) {
                helper(a, depth + 1, v);
            }
        }
    }
其实上面的方法可以简化,由于每一层的数字不用分别保存,每个数字分别乘以深度再相加,跟每层数字先相加起来再乘以深度是一样的,这样我们只需要一个一维数组就可以了,只要把各层的数字和保存起来,最后再计算权重和即可:
    int depthSumInverse(vector<NestedInteger>& nestedList) {
        int res = 0;
        vector<int> v;
        for (auto a : nestedList) {
            helper(a, 0, v);
        }
        for (int i = v.size() - 1; i >= 0; --i) {
            res += v[i] * (v.size() - i);
        }
        return res;
    }
    void helper(NestedInteger ni, int depth, vector<int> &v) {
        if (depth >= v.size()) v.resize(depth + 1);
        if (ni.isInteger()) {
            v[depth] += ni.getInteger();
        } else {
            for (auto a : ni.getList()) {
                helper(a, depth + 1, v);
            }
        }
    }

Labels

LeetCode (1432) GeeksforGeeks (1122) LeetCode - Review (1067) Review (882) Algorithm (668) to-do (609) Classic Algorithm (270) Google Interview (237) Classic Interview (222) Dynamic Programming (220) DP (186) Bit Algorithms (145) POJ (141) Math (137) Tree (132) LeetCode - Phone (129) EPI (122) Cracking Coding Interview (119) DFS (115) Difficult Algorithm (115) Lintcode (115) Different Solutions (110) Smart Algorithm (104) Binary Search (96) BFS (91) HackerRank (90) Binary Tree (86) Hard (79) Two Pointers (78) Stack (76) Company-Facebook (75) BST (72) Graph Algorithm (72) Time Complexity (69) Greedy Algorithm (68) Interval (63) Company - Google (62) Geometry Algorithm (61) Interview Corner (61) LeetCode - Extended (61) Union-Find (60) Trie (58) Advanced Data Structure (56) List (56) Priority Queue (53) Codility (52) ComProGuide (50) LeetCode Hard (50) Matrix (50) Bisection (48) Segment Tree (48) Sliding Window (48) USACO (46) Space Optimization (45) Company-Airbnb (41) Greedy (41) Mathematical Algorithm (41) Tree - Post-Order (41) ACM-ICPC (40) Algorithm Interview (40) Data Structure Design (40) Graph (40) Backtracking (39) Data Structure (39) Jobdu (39) Random (39) Codeforces (38) Knapsack (38) LeetCode - DP (38) Recursive Algorithm (38) String Algorithm (38) TopCoder (38) Sort (37) Introduction to Algorithms (36) Pre-Sort (36) Beauty of Programming (35) Must Known (34) Binary Search Tree (33) Follow Up (33) prismoskills (33) Palindrome (32) Permutation (31) Array (30) Google Code Jam (30) HDU (30) Array O(N) (29) Logic Thinking (29) Monotonic Stack (29) Puzzles (29) Code - Detail (27) Company-Zenefits (27) Microsoft 100 - July (27) Queue (27) Binary Indexed Trees (26) TreeMap (26) to-do-must (26) 1point3acres (25) GeeksQuiz (25) Merge Sort (25) Reverse Thinking (25) hihocoder (25) Company - LinkedIn (24) Hash (24) High Frequency (24) Summary (24) Divide and Conquer (23) Proof (23) Game Theory (22) Topological Sort (22) Lintcode - Review (21) Tree - Modification (21) Algorithm Game (20) CareerCup (20) Company - Twitter (20) DFS + Review (20) DP - Relation (20) Brain Teaser (19) DP - Tree (19) Left and Right Array (19) O(N) (19) Sweep Line (19) UVA (19) DP - Bit Masking (18) LeetCode - Thinking (18) KMP (17) LeetCode - TODO (17) Probabilities (17) Simulation (17) String Search (17) Codercareer (16) Company-Uber (16) Iterator (16) Number (16) O(1) Space (16) Shortest Path (16) itint5 (16) DFS+Cache (15) Dijkstra (15) Euclidean GCD (15) Heap (15) LeetCode - Hard (15) Majority (15) Number Theory (15) Rolling Hash (15) Tree Traversal (15) Brute Force (14) Bucket Sort (14) DP - Knapsack (14) DP - Probability (14) Difficult (14) Fast Power Algorithm (14) Pattern (14) Prefix Sum (14) TreeSet (14) Algorithm Videos (13) Amazon Interview (13) Basic Algorithm (13) Codechef (13) Combination (13) Computational Geometry (13) DP - Digit (13) LCA (13) LeetCode - DFS (13) Linked List (13) Long Increasing Sequence(LIS) (13) Math-Divisible (13) Reservoir Sampling (13) mitbbs (13) Algorithm - How To (12) Company - Microsoft (12) DP - Interval (12) DP - Multiple Relation (12) DP - Relation Optimization (12) LeetCode - Classic (12) Level Order Traversal (12) Prime (12) Pruning (12) Reconstruct Tree (12) Thinking (12) X Sum (12) AOJ (11) Bit Mask (11) Company-Snapchat (11) DP - Space Optimization (11) Dequeue (11) Graph DFS (11) MinMax (11) Miscs (11) Princeton (11) Quick Sort (11) Stack - Tree (11) 尺取法 (11) 挑战程序设计竞赛 (11) Coin Change (10) DFS+Backtracking (10) Facebook Hacker Cup (10) Fast Slow Pointers (10) HackerRank Easy (10) Interval Tree (10) Limited Range (10) Matrix - Traverse (10) Monotone Queue (10) SPOJ (10) Starting Point (10) States (10) Stock (10) Theory (10) Tutorialhorizon (10) Kadane - Extended (9) Mathblog (9) Max-Min Flow (9) Maze (9) Median (9) O(32N) (9) Quick Select (9) Stack Overflow (9) System Design (9) Tree - Conversion (9) Use XOR (9) Book Notes (8) Company-Amazon (8) DFS+BFS (8) DP - States (8) Expression (8) Longest Common Subsequence(LCS) (8) One Pass (8) Quadtrees (8) Traversal Once (8) Trie - Suffix (8) 穷竭搜索 (8) Algorithm Problem List (7) All Sub (7) Catalan Number (7) Cycle (7) DP - Cases (7) Facebook Interview (7) Fibonacci Numbers (7) Flood fill (7) Game Nim (7) Graph BFS (7) HackerRank Difficult (7) Hackerearth (7) Inversion (7) Kadane’s Algorithm (7) Manacher (7) Morris Traversal (7) Multiple Data Structures (7) Normalized Key (7) O(XN) (7) Radix Sort (7) Recursion (7) Sampling (7) Suffix Array (7) Tech-Queries (7) Tree - Serialization (7) Tree DP (7) Trie - Bit (7) 蓝桥杯 (7) Algorithm - Brain Teaser (6) BFS - Priority Queue (6) BFS - Unusual (6) Classic Data Structure Impl (6) DP - 2D (6) DP - Monotone Queue (6) DP - Unusual (6) DP-Space Optimization (6) Dutch Flag (6) How To (6) Interviewstreet (6) Knapsack - MultiplePack (6) Local MinMax (6) MST (6) Minimum Spanning Tree (6) Number - Reach (6) Parentheses (6) Pre-Sum (6) Probability (6) Programming Pearls (6) Rabin-Karp (6) Reverse (6) Scan from right (6) Schedule (6) Stream (6) Subset Sum (6) TSP (6) Xpost (6) n00tc0d3r (6) reddit (6) AI (5) Abbreviation (5) Anagram (5) Art Of Programming-July (5) Assumption (5) Bellman Ford (5) Big Data (5) Code - Solid (5) Code Kata (5) Codility-lessons (5) Coding (5) Company - WMware (5) Convex Hull (5) Crazyforcode (5) DFS - Multiple (5) DFS+DP (5) DP - Multi-Dimension (5) DP-Multiple Relation (5) Eulerian Cycle (5) Graph - Unusual (5) Graph Cycle (5) Hash Strategy (5) Immutability (5) Java (5) LogN (5) Manhattan Distance (5) Matrix Chain Multiplication (5) N Queens (5) Pre-Sort: Index (5) Quick Partition (5) Quora (5) Randomized Algorithms (5) Resources (5) Robot (5) SPFA(Shortest Path Faster Algorithm) (5) Shuffle (5) Sieve of Eratosthenes (5) Strongly Connected Components (5) Subarray Sum (5) Sudoku (5) Suffix Tree (5) Swap (5) Threaded (5) Tree - Creation (5) Warshall Floyd (5) Word Search (5) jiuzhang (5)

Popular Posts