Nested List Weight Sum
原題鏈接在這里(付費(fèi)):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)
分析:
【簡單思路】設(shè)置一個(gè)depth變量,每遇一次左括號(hào)加1测秸,遇一次右括號(hào)減1。然后再設(shè)置一個(gè)sum自增變量灾常。在加減之中霎冯,讓depth與括號(hào)中的數(shù)相乘得出的積加到sum中。需要注意的是钞瀑,如果字符串很長沈撞,就可能需要?jiǎng)h減。
【進(jìn)階思路】采用dfs算法雕什,dfs的遞歸有加就有減关串。