Skip to content

Commit 0953381

Browse files
committed
Time: 7 ms (54.05%), Space: 45.2 MB (41.66%) - LeetHub
1 parent 04171a7 commit 0953381

File tree

1 file changed

+67
-0
lines changed

1 file changed

+67
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
/*
2+
3+
931. 최소 하강 경로 합계
4+
5+
정수 행렬의 n x n 배열이 주어졌을 때,
6+
7+
행렬을 통과하는 모든 하강 경로의 최소 합을 반환합니다.
8+
9+
하강 경로는 첫 번째 행의 임의의 요소에서 시작하여
10+
11+
다음 행의 바로 아래 또는 대각선 왼쪽/오른쪽에 있는 요소를 선택합니다.
12+
13+
구체적으로, (행, 열) 위치에서 다음 요소는 (행 + 1, 열 - 1), (행 + 1, 열) 또는 (행 + 1, 열 + 1)이 될 것입니다.
14+
15+
예시 1:
16+
17+
입력: matrix = [[2,1,3],[6,5,4],[7,8,9]]
18+
19+
Output: 13
20+
21+
설명: 설명: 아래와 같이 최소 합이 있는 두 개의 하강 경로가 있습니다.
22+
23+
예제 2:
24+
25+
입력: matrix = [[-19,57],[-40,-5]]
26+
27+
Output: -59
28+
29+
설명: 설명: 최소 합이 있는 하강 경로를 표시합니다.
30+
31+
제약 조건:
32+
33+
n == matrix.length == matrix[i].length
34+
35+
1 <= n <= 100
36+
37+
-100 <= matrix[i][j] <= 100
38+
39+
*/
40+
41+
class Solution {
42+
43+
public int minFallingPathSum(int[][] matrix) {
44+
45+
int n = matrix.length;
46+
int[][] dp = new int[n][n];
47+
int min = Integer.MAX_VALUE;
48+
49+
for (int i = 0; i < n; i++) {
50+
dp[0][i] = matrix[0][i];
51+
}
52+
53+
for (int i = 1; i < n; i++) {
54+
for (int j = 0; j < n; j++) {
55+
if(j == 0) dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j+1]) + matrix[i][j];
56+
else if (j == n-1) dp[i][j] = Math.min(dp[i-1][j], dp[i-1][j-1]) + matrix[i][j];
57+
else dp[i][j] = Math.min(dp[i-1][j-1], Math.min(dp[i-1][j], dp[i-1][j+1])) + matrix[i][j];
58+
}
59+
}
60+
61+
for (int i = 0; i < n; i++) {
62+
min = Math.min(min, dp[n-1][i]);
63+
}
64+
65+
return min;
66+
}
67+
}

0 commit comments

Comments
 (0)