LeetCode 339. 嵌套列表权重和(DFS)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 339. 嵌套列表权重和(DFS)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
給定一個嵌套的整數列表,請返回該列表按深度加權后所有整數的總和。
每個元素要么是整數,要么是列表。同時,列表中元素同樣也可以是整數或者是另一個列表。
示例 1: 輸入: [[1,1],2,[1,1]] 輸出: 10 解釋: 因為列表中有四個深度為 2 的 1 ,和一個深度為 1 的 2。示例 2: 輸入: [1,[4,[6]]] 輸出: 27 解釋: 一個深度為 1 的 1,一個深度為 2 的 4,一個深度為 3 的 6。 所以,1 + 4*2 + 6*3 = 27。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/nested-list-weight-sum
著作權歸領扣網絡所有。商業轉載請聯系官方授權,非商業轉載請注明出處。
2. 解題
類似題目:LeetCode 364. 加權嵌套序列和 II(重復疊加)
/*** // This is the interface that allows for creating nested lists.* // You should not implement it, or speculate about its implementation* class NestedInteger {* public:* // Constructor initializes an empty nested list.* * NestedInteger();** // Constructor initializes a single integer.* * NestedInteger(int value);** // Return true if this NestedInteger holds a single integer, rather than a nested list.* * bool isInteger() const;** // Return the single integer that this NestedInteger holds, if it holds a single integer* // The result is undefined if this NestedInteger holds a nested list* * int getInteger() const;** // Set this NestedInteger to hold a single integer.* * void setInteger(int value);** // Set this NestedInteger to hold a nested list and adds a nested integer to it.* * void add(const NestedInteger &ni);** // Return the nested list that this NestedInteger holds, if it holds a nested list* // The result is undefined if this NestedInteger holds a single integer* * const vector<NestedInteger> &getList() const;* };*/ class Solution {int ans = 0; public:int depthSum(vector<NestedInteger>& nestedList) {if(nestedList.empty()) return 0;dfs(nestedList,1);return ans;}void dfs(vector<NestedInteger> &nestedList, int deep){for(int i = 0; i < nestedList.size(); ++i){if(nestedList[i].isInteger())ans += nestedList[i].getInteger() * deep;elsedfs(nestedList[i].getList(),deep+1);}} };4 ms 8.3 MB
長按或掃碼關注我的公眾號,一起加油、一起學習進步!
總結
以上是生活随笔為你收集整理的LeetCode 339. 嵌套列表权重和(DFS)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 390. 消除游戏(类
- 下一篇: LeetCode 983. 最低票价(动