算法题LC41:triangle

动态规划:
题目描述
给出一个三角形,计算从三角形顶部到底部的最小路径和,每一步都可以移动到下面一行相邻的数字,
例如,给出的三角形如下:
[↵ [2],↵ [3,4],↵ [6,5,7],↵ [4,1,8,3]↵]
最小的从顶部到底部的路径和是2 + 3 + 5 + 1 = 11。
注意:
如果你能只用O(N)的额外的空间来完成这项工作的话,就可以得到附加分,其中N是三角形中的行总数。

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 is11(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.

输入描述

输出描述

示例1:
输入

输出
        
代码:

import java.util.ArrayList;
/*
可以发现一个规律:第l个数组的第k个元素的下一个元素的有两种可能,分别是第l+1个数组的第k个元素与第k+1个元素。所以递归取最小值搞定
*/
public class Solution {
    public int minimumTotal(ArrayList<ArrayList<Integer>> triangle) {
        int sum ;
        sum = getResult(triangle,0,0);
        return sum;
    }
    public int getResult(ArrayList<ArrayList<Integer>> triangle,int l,int k) {
        int sum = triangle.get(l).get(k);
        if(l<triangle.size()-1)
             sum = sum+Math.min(getResult(triangle,l+1,k),getResult(triangle,l+1,k+1));
        return sum;
    }
}
发布了80 篇原创文章 · 获赞 1 · 访问量 1407

猜你喜欢

转载自blog.csdn.net/alidingding/article/details/104673262
今日推荐