日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

LeetCode 339. 嵌套列表权重和(DFS)

發(fā)布時(shí)間:2024/7/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 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è)深度為 21 ,和一個(gè)深度為 12。示例 2: 輸入: [1,[4,[6]]] 輸出: 27 解釋: 一個(gè)深度為 11,一個(gè)深度為 24,一個(gè)深度為 36。 所以,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)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。