LeetCode 339. 嵌套列表权重和(DFS)
生活随笔
收集整理的這篇文章主要介紹了
LeetCode 339. 嵌套列表权重和(DFS)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
文章目錄
- 1. 題目
- 2. 解題
1. 題目
給定一個(gè)嵌套的整數(shù)列表,請(qǐng)返回該列表按深度加權(quán)后所有整數(shù)的總和。
每個(gè)元素要么是整數(shù),要么是列表。同時(shí),列表中元素同樣也可以是整數(shù)或者是另一個(gè)列表。
示例 1: 輸入: [[1,1],2,[1,1]] 輸出: 10 解釋: 因?yàn)榱斜碇杏兴膫€(gè)深度為 2 的 1 ,和一個(gè)深度為 1 的 2。示例 2: 輸入: [1,[4,[6]]] 輸出: 27 解釋: 一個(gè)深度為 1 的 1,一個(gè)深度為 2 的 4,一個(gè)深度為 3 的 6。 所以,1 + 4*2 + 6*3 = 27。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/nested-list-weight-sum
著作權(quán)歸領(lǐng)扣網(wǎng)絡(luò)所有。商業(yè)轉(zhuǎn)載請(qǐng)聯(lián)系官方授權(quán),非商業(yè)轉(zhuǎn)載請(qǐng)注明出處。
2. 解題
類似題目:LeetCode 364. 加權(quán)嵌套序列和 II(重復(fù)疊加)
/*** // 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
長按或掃碼關(guān)注我的公眾號(hào),一起加油、一起學(xué)習(xí)進(jìn)步!
總結(jié)
以上是生活随笔為你收集整理的LeetCode 339. 嵌套列表权重和(DFS)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: LeetCode 390. 消除游戏(类
- 下一篇: LeetCode 983. 最低票价(动