And minimum path
LeetCode: minimum path and
Subject description:
Given a non-negative integer of mxn grid, find a path from left to bottom right, so that the sum of the minimum number of paths.
Note: you can only move one step down or to the right.
Example:
输入:
[
[1,3,1],
[1,5,1],
[4,2,1]
]
输出: 7
解释: 因为路径 1→3→1→1→1 的总和最小。
thought:
Dynamic programming, you can use the original array as an array dp
Code:
class Solution {
public int minPathSum(int[][] grid) {
int i=0,j=0;
for(i=0;i<grid.length;++i){
for(j=0;j<grid[0].length;++j){
if(i>0&&j>0){
grid[i][j]+= Math.min(grid[i-1][j],grid[i][j-1]);
}else{
grid[i][j]+= (i==0?0:grid[i-1][j]) + (j==0?0:grid[i][j-1]);
}
}
}
return grid[i-1][j-1];
}
}
Triangles and minimum path
LeetCode: triangles, and minimum path
Subject description:
Given a triangle, find the minimum and the top-down path. Each step can move to the next line adjacent nodes.
If you can use only O (n) extra space (n number of rows as a triangle) to solve this problem, then your algorithm will be a plus.
Example:
例如给定三角形
[
[2],
[3,4],
[6,5,7],
[4,1,8,3]
]
自顶向下的最小路径和为 11(即,2 + 3 + 5 + 1 = 11)。
thought:
From the bottom up, modify array dp
Code:
The first method: modified on the source array. Such seemingly inefficient.
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
for(int i=triangle.size()-2;i>=0;--i){
for(int j=0;j<i+1;++j){
triangle.get(i).set(j,triangle.get(i).get(j)+Math.min(triangle.get(i+1).get(j+1),triangle.get(i+1).get(j)));
}
}
return triangle.get(0).get(0);
}
}
The second method: set up an array of dp, dp modify the array; note that this is very clever, every modification will not affect the judgment of the next cycle; second, each cycle, the last number will not change it until the last round , plus the number of the top, the final result dp [0].
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int len = triangle.size();
int[] dp=new int[len];
for(int i=0;i<len;++i){
dp[i]=triangle.get(len-1).get(i);
}
for(int i=len-2;i>=0;--i){
for(int j=0;j<i+1;++j){
dp[j] = Math.min(dp[j],dp[j+1]) + triangle.get(i).get(j);
}
}
return dp[0];
}
}