首页 > 代码库 > LeetCode - Trangle
LeetCode - Trangle
这道题,采用动态规划算法。from top to down,把到每个节点的最小路径和都求出来。
下面是AC代码:
1 /** 2 * Given a triangle, find the minimum path sum from top to bottom. 3 * Each step you may move to adjacent numbers on the row below. 4 * @param triangle 5 * @return 6 */ 7 public int minimumTotal(ArrayList<ArrayList<Integer>> triangle){ 8 if(triangle==null || triangle.size()<=0) 9 return 0; 10 if(triangle.size() == 1) 11 return triangle.get(0).get(0); 12 ArrayList<Integer> last = triangle.get(0); 13 ArrayList<Integer> curr = new ArrayList<Integer>(); 14 //through Dynamic programming 15 for(int i=1;i<triangle.size();i++){ 16 curr.add(last.get(0)+triangle.get(i).get(0)); 17 for(int j=1;j<i;j++){ 18 //get the smaller adjacent one on the last row 19 curr.add((last.get(j-1)<last.get(j)?last.get(j-1):last.get(j))+triangle.get(i).get(j)); 20 } 21 curr.add(last.get(i-1)+triangle.get(i).get(i)); 22 last.clear(); 23 last.addAll(curr); 24 curr.clear(); 25 } 26 27 int min = Integer.MAX_VALUE; 28 for(int i=0;i<last.size();i++){ 29 if(last.get(i)<min) 30 min = last.get(i); 31 } 32 return min; 33 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。