1. 程式人生 > >[LeetCode] Nested List Weight Sum 巢狀連結串列權重和

[LeetCode] 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:
Given the list [[1,1],2,[1,1]], return 10. (four 1's at depth 2, one 2 at depth 1)

Example 2:


Given the list [1,[4,[6]]], return 27. (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;
    }
};

參考資料: