【LeetCode] 364加重ネストされた配列とII(DFS)

タイトル

整数のネストされたシーケンスに、各数の加重和に戻ってください、彼らの深さの順に、その量は重量で決まります。

配列の各要素は、整数または配列(SEQこの配列の各要素又はも整数)のいずれかです。

この体重の問題の重みは、ルートへの葉から1ずつ増加しながら、元の1つの問題は、葉の付け根から1による重量増加の一つに記載の右質問する前に、異なっています。

言い換えれば、この質問では、1の葉の重量の、ルート最大の重みを有しています。

例1:

入力:[1,1]、2、[1,1]
出力:8
説明:1 2の深さの位置に4箇所1,2の深さで。
例2:

入力:[1、[4、[6]]]
出力:17
説明:1深さ位置での1の深さの位置での2,6の深さの位置で3、4です。1 3 + 4 2 + 6 * 1 = 17。

出典:滞在ボタン(LeetCode)
//leetcode-cn.com/problems/nested-list-weight-sum-ii:リンク:httpsの
すべてのネットワークからの控除が著作権を保有。商業転載は、ソースを明記してください許可公式、非商用の転載をご連絡ください。

問題の解決策

最大深さを計算するために、二回最初のパスのDFSを使用して、重み付け第二のパスを計算します。
PS:もしコントラストの計算深さ、重み付き和計算DF回のみ。

コード

/**
 * // This is the interface that allows for creating nested lists.
 * // You should not implement it, or speculate about its implementation
 * public interface NestedInteger {
 *     // Constructor initializes an empty nested list.
 *     public NestedInteger();
 *
 *     // Constructor initializes a single integer.
 *     public NestedInteger(int value);
 *
 *     // @return true if this NestedInteger holds a single integer, rather than a nested list.
 *     public boolean isInteger();
 *
 *     // @return the single integer that this NestedInteger holds, if it holds a single integer
 *     // Return null if this NestedInteger holds a nested list
 *     public Integer getInteger();
 *
 *     // Set this NestedInteger to hold a single integer.
 *     public void setInteger(int value);
 *
 *     // Set this NestedInteger to hold a nested list and adds a nested integer to it.
 *     public void add(NestedInteger ni);
 *
 *     // @return the nested list that this NestedInteger holds, if it holds a nested list
 *     // Return null if this NestedInteger holds a single integer
 *     public List<NestedInteger> getList();
 * }
 */
class Solution {
    private int maxDepth=0;

    public int depthSumInverse(List<NestedInteger> nestedList) {
        updateMaxDepth(nestedList,1);
        return getDepthSum(nestedList,1);
    }

    private void updateMaxDepth(List<NestedInteger> nestedList,int depth){
        for(NestedInteger nestedInteger:nestedList){
            if(nestedInteger.isInteger()){
                maxDepth=depth>maxDepth?depth:maxDepth;
            }
            else {
                updateMaxDepth(nestedInteger.getList(),depth+1);
            }
        }
    }

    private int getDepthSum(List<NestedInteger> nestedList,int depth){
        int sum=0;
        for(NestedInteger nestedInteger:nestedList){
            if(nestedInteger.isInteger()){
                sum+=(maxDepth-depth+1) * nestedInteger.getInteger();
            }
            else{
                sum+=getDepthSum(nestedInteger.getList(),depth+1);
            }
        }
        return sum;
    }
}

おすすめ

転載: www.cnblogs.com/coding-gaga/p/12306019.html