[LeetCode] 339. Nested List Weight Sum 嵌套鏈表權重和


 

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.

Example 1:

Input: [[1,1],2,[1,1]]
Output: 10 Explanation: Four 1's at depth 2, one 2 at depth 1.

Example 2:

Input: [1,[4,[6]]]
Output: 27 Explanation: One 1 at depth 1, one 4 at depth 2, and one 6 at depth 3; 1 + 4*2 + 6*3 = 27.

 

這道題定義了一種嵌套鏈表的結構,鏈表可以無限往里嵌套,規定每嵌套一層,深度加1,讓我們求權重之和,就是每個數字乘以其權重,再求總和。那么我們考慮,由於嵌套層數可以很大,所以我們用深度優先搜索DFS會很簡單,每次遇到嵌套的,遞歸調用函數,一層一層往里算就可以了,我最先想的方法是遍歷給的嵌套鏈表的數組,對於每個嵌套鏈表的對象,調用getSum函數,並賦深度值1,累加起來返回。在getSum函數中,首先判斷其是否為整數,如果是,則返回當前深度乘以整數,如果不是,那么我們再遍歷嵌套數組,對每個嵌套鏈表再調用遞歸函數,將返回值累加起來返回即可,參見代碼如下:

 

解法一:

class Solution {
public:
    int depthSum(vector<NestedInteger>& nestedList) {
        int res = 0;
        for (auto a : nestedList) {
            res += getSum(a, 1);
        }
        return res;
    }
    int getSum(NestedInteger ni, int level) {
        int res = 0;
        if (ni.isInteger()) return level * ni.getInteger();
        for (auto a : ni.getList()) {
            res += getSum(a, level + 1);
        }
        return res;
    }
};

 

但其實上面的方法可以優化,我們可以把給的那個嵌套鏈表的一維數組直接當做一個嵌套鏈表的對象,然后調用遞歸函數,遞歸函數的處理方法跟上面一樣,只不過用了個三元處理使其看起來更加簡潔了一些:

 

解法二:

class Solution {
public:
    int depthSum(vector<NestedInteger>& nestedList) {
        return helper(nestedList, 1);
    }
    int helper(vector<NestedInteger>& nl, int depth) {
        int res = 0;
        for (auto a : nl) {
            res += a.isInteger() ? a.getInteger() * depth : helper(a.getList(), depth + 1);
        }
        return res;
    }
};

 

參考資料:

https://leetcode.com/problems/nested-list-weight-sum/

https://leetcode.com/discuss/94956/2ms-easy-to-understand-java-solution

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM