1. 程式人生 > >LeetCode 339. Nested List Weight Sum (嵌套列表重和)

LeetCode 339. Nested List Weight Sum (嵌套列表重和)

cnblogs one time lists lds all logs sts not

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)


題目標簽:Depth First Search

  這道題目給了我們一個嵌套的list,在這個list裏,每一個element可以是一個integer,又可以是一個list,這個list裏還可以繼續有list,可以無限套。所以要用到depth first search。如果能走到最裏面一層呢,要利用recursive function,一層一層遞歸下去直到它是一個integer了,就可以返回了。所以需要另外一個function getSum。首先iterate nestedList, 把每一個element 加起來。 為了得到這個element的值,我們要把它代入getSum function, 如果這個element 是integer 直接return。 如果這個element 是一個list,那麽利用相同的方法,設一個sum 把它每一個element 加起來,為了得到每一個element,把每一個element代入getSum,記得這裏要把depth + 1。因為我們代入了下一層depth。

Java Solution:

Runtime beats 6.27%

完成日期:07/09/2017

關鍵詞:Depth First Search

關鍵點:利用遞歸function來實現depth first search

 1 /**
 2  * // This is the interface that allows for creating nested lists.
 3  * // You should not implement it, or speculate about its implementation
 4  * public interface NestedInteger {
5 * 6 * // @return true if this NestedInteger holds a single integer, rather than a nested list. 7 * public boolean isInteger(); 8 * 9 * // @return the single integer that this NestedInteger holds, if it holds a single integer 10 * // Return null if this NestedInteger holds a nested list 11 * public Integer getInteger(); 12 * 13 * // @return the nested list that this NestedInteger holds, if it holds a nested list 14 * // Return null if this NestedInteger holds a single integer 15 * public List<NestedInteger> getList(); 16 * } 17 */ 18 public class Solution 19 { 20 public int depthSum(List<NestedInteger> nestedList) 21 { 22 int res = 0; 23 24 // iterate list 25 for(int i=0; i<nestedList.size(); i++) 26 res += getSum(nestedList.get(i), 1); 27 28 return res; 29 } 30 31 public int getSum(NestedInteger ele, int depth) 32 { 33 int sum = 0; 34 35 // if ele is integer, return its value * depth; 36 if(ele.isInteger()) 37 return depth * ele.getInteger(); 38 39 // if ele is a list, iterate list recursively call function; 40 for(int i=0; i<ele.getList().size(); i++) 41 sum += getSum(ele.getList().get(i), depth + 1); 42 43 44 return sum; 45 } 46 }

參考資料:

http://www.cnblogs.com/grandyang/p/5340305.html

LeetCode 算法題目列表 - LeetCode Algorithms Questions List

LeetCode 339. Nested List Weight Sum (嵌套列表重和)