Triangle

Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.

For example, given the following triangle

[
     [2],
    [3,4],
   [6,5,7],
  [4,1,8,3]
]

 

The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).

Note:
Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.

思路:记录最后一行sum,然后求出最小值

注意事项:由于下一行比上一行多一个值,所以要从后向前覆盖

java代码:

  1. public int minimumTotal(List<List<Integer>> triangle) {
  2. if(triangle==null) return 0;
  3. int high = triangle.size();
  4. if(high==0) return 0;
  5. int[] result = new int[high];
  6. int final_value = Integer.MAX_VALUE;
  7. for(int i=0;i<high;i++) {
  8. int j=0;
  9. List<Integer> line = triangle.get(i);
  10. for(j=line.size()-1;j>=0;j--) {
  11. if(i==0) {
  12. result[j] =line.get(j);
  13. } else {
  14. if(j==0) result[0] = result[0] + line.get(0);
  15. else if(j==line.size()-1) {
  16. result[j] = result[j-1] + line.get(j);
  17. }
  18. else {
  19. if(result[j-1] > result[j])
  20. result[j] = result[j] + line.get(j);
  21. else
  22. result[j] = result[j-1] + line.get(j);
  23. }
  24. }
  25. if(i==high-1) {
  26. if(result[j] < final_value) {
  27. final_value = result[j];
  28. }
  29. }
  30. }
  31. }
  32. return final_value;
  33. }

C++代码: 从后向前

  1. int minimumTotal(vector<vector<int> > &triangle) {
  2. if(triangle.empty()) return 0;
  3. vector<int> flag;
  4. int high = triangle.size();
  5. flag.resize(triangle[high-1].size());
  6. for(int i=high-1;i>=0;i--) {
  7. int width = triangle[i].size();
  8. for(int j=0;j<width;j++) {
  9. if(i==high-1) flag[j] = triangle[i][j];
  10. else flag[j] = triangle[i][j] + min(flag[j],flag[j+1]);
  11. }
  12. }
  13. return flag[0];
  14. }
posted @ 2014-08-02 14:15  purejade  阅读(112)  评论(0)    收藏  举报