Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commita8ecd72

Browse files
minimum path sum
1 parent19b62b4 commita8ecd72

File tree

1 file changed

+65
-0
lines changed

1 file changed

+65
-0
lines changed

‎MEDIUM/src/medium/MinimumPathSum.java

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
packagemedium;
2+
3+
importutils.CommonUtils;
4+
5+
/**64. Minimum Path Sum
6+
7+
Total Accepted: 78724
8+
Total Submissions: 219899
9+
Difficulty: Medium
10+
11+
Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right which minimizes the sum of all numbers along its path.
12+
13+
Note: You can only move either down or right at any point in time.*/
14+
publicclassMinimumPathSum {
15+
/**Same idea as ClimbingStairs, also typical trick:
16+
* have to initialize the first row and the first column and start the for loop from i==1 and j==1 for the rest
17+
* of the matrix.*/
18+
publicintminPathSum(int[][]grid) {
19+
if(grid ==null ||grid.length ==0)return0;
20+
21+
intheight =grid.length,width =grid[0].length;
22+
int[][]dp =newint[height][width];
23+
dp[0][0] =grid[0][0];
24+
for(inti =1;i <height;i++){
25+
dp[i][0] =dp[i-1][0] +grid[i][0];
26+
}
27+
for(intj =1;j <width;j++){
28+
dp[0][j] =dp[0][j-1] +grid[0][j];
29+
}
30+
for(inti =1;i <height;i++){
31+
for(intj =1;j <width;j++){
32+
dp[i][j] =Math.min(dp[i-1][j],dp[i][j-1]) +grid[i][j];
33+
}
34+
}
35+
CommonUtils.printMatrix(dp);
36+
returndp[height-1][width-1];
37+
}
38+
39+
publicstaticvoidmain(String...strings){
40+
MinimumPathSumtest =newMinimumPathSum();
41+
// int[][] grid = new int[2][2];
42+
// grid[0][0] = 1;
43+
// grid[0][1] = 2;
44+
// grid[1][0] = 1;
45+
// grid[1][1] = 1;
46+
47+
// int[][] grid = new int[1][1];
48+
// grid[0][0] = 1;
49+
50+
int[][]grid =newint[3][3];
51+
grid[0][0] =1;
52+
grid[0][1] =3;
53+
grid[0][2] =1;
54+
grid[1][0] =1;
55+
grid[1][1] =5;
56+
grid[1][2] =1;
57+
grid[2][0] =4;
58+
grid[2][1] =2;
59+
grid[2][2] =1;
60+
61+
62+
CommonUtils.printMatrix(grid);
63+
System.out.println(test.minPathSum(grid));
64+
}
65+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp