364. Nested List Weight Sum II
這個題做了一個多小時,好傻逼。
顯而易見計算的話必須知道當前層是第幾層,因為要乘權重,想要知道是第幾層又必須知道最高是幾層。。
用了好久是因為想ONE PASS,嘗試過遍歷的時候構建STACK,通過和頂端的距離來判定層數,但是其實最后POP的過程相當于又遍歷了一次。而且STACK無法O(1) access,換成LIST需要手動來維持順序。
最終放棄了,看答案。。發現都是先遍歷一次得到最高權重。。。。。。仔細想想似乎1-PASS可以用MAP實現,但是每次發現新高權重,就必須更新以前所有的,貌似沒必要1PASS。。。
如果不要求1PASS,先遍歷算權重的話,這個題就很直白了。。
public class Solution {int depth;public int depthSumInverse(List<NestedInteger> nestedList) {if(nestedList.size() == 0) return 0;depth = getDepth(nestedList);return helper(nestedList,1);}public int getDepth(List<NestedInteger> list){int res = 1;for(NestedInteger n: list)if(!n.isInteger()) res = Math.max(res,getDepth(n.getList())+1);return res;}public int helper(List<NestedInteger> list, int curLevel){int res = 0;for(NestedInteger i: list)if(i.isInteger()){res += (depth+1-curLevel)*i.getInteger();}else{res +=helper(i.getList(),curLevel+1);}return res;}}二刷。
這個題也有印象,一刷的時候嘗試1-PASS的DFS,根本不可能。
BFS倒是可以,模擬level order traversal。很重要的一點就是要保留積累值,代碼里我用的cum= =baby cum..cum..
重點是。。每到新的一層,返還結果都加一遍積累值,就可以滿足權重weighted的關系。最早的我想法乘,DFS找到權重然后乘第幾層,但是實際上這里反倒是返璞歸真,加法最適合這種方式,而乘法根本難以表示這種關系。。
總共N層,最上面的一層作為積累制存在的N次,總共被加到res里N次,正好是這個題的意思。。
public class Solution {public int depthSumInverse(List<NestedInteger> nestedList) {if (nestedList.size() == 0) return 0;int res = 0;int cum = 0;List<NestedInteger> tempList = new LinkedList<>();while (true) {for (NestedInteger i : nestedList) {if (i.isInteger()) {cum += i.getInteger();} else {tempList.addAll(i.getList());}}res += cum;if (tempList.size() == 0) {return res;} else {nestedList = tempList;tempList = new ArrayList<>();}}} }所以結果是可以1-pass的。
DFS就先走一遍,找到最深的層數,然后遞歸并添加一個當前參數代表當前層數,層數差表示他出現的次數。
意淫完回頭一看一刷,就是這么做的,我真是毫無長進。。。
轉載于:https://www.cnblogs.com/reboot329/p/5944469.html
總結
以上是生活随笔為你收集整理的364. Nested List Weight Sum II的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【手把手】JavaWeb 入门级项目实战
- 下一篇: 梯度下降法与牛顿法的比较