leetcode “120. triangle”

LeetCode link

Intuition

  • Try DFS. Maybe have a TLE.

solution

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
int min = Integer.MAX_VALUE;
public int minimumTotal(List<List<Integer>> triangle) {
this.helper(triangle, 0, 0, 0);
return min;
}
private void helper(List<List<Integer>> triangle, int row, int col, int sum) {
if (row >= triangle.size()) {
min = Math.min(min, sum);
return;
}
List<Integer> line = triangle.get(row);
if (col >= line.size()) {
return;
}
this.helper(triangle, row + 1, col, sum + line.get(col));
if (col + 1 < line.size()) {
this.helper(triangle, row + 1, col + 1, sum + line.get(col + 1));
}
}
}

problem

With no doubt, TLE


modification

Using DP.

  • Save a 2d-array to save the min total when reach the current position.
  • When reach the last row, compare the min.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int rows = triangle.size();
int largestCol = triangle.get(rows - 1).size();
int[][] dp = new int[rows][largestCol];
List<Integer> firstLine = triangle.get(0);
int min = Integer.MAX_VALUE;
for (int i = 0; i < firstLine.size(); i++) {
dp[0][i] = firstLine.get(i);
min = Math.min(min, dp[0][i]);
}
if (rows <= 1) {
return min;
}
for (int i = 1; i < rows - 1; i++) {
List<Integer> line = triangle.get(i);
dp[i][0] = dp[i - 1][0] + line.get(0);
int j = 1;
for (j = 1; j < line.size() - 1; j++) {
dp[i][j] = Math.min(dp[i - 1][j - 1], dp[i - 1][j]) + line.get(j);
}
dp[i][j] = dp[i - 1][j - 1] + line.get(j);
}
List<Integer> lastLine = triangle.get(rows - 1);
min = dp[rows - 2][0] + lastLine.get(0);
int j = 1;
for (j = 1; j < lastLine.size() - 1; j++) {
dp[rows - 1][j] = Math.min(dp[rows - 2][j - 1], dp[rows - 2][j]) + lastLine.get(j);
min = Math.min(min, dp[rows - 1][j]);
}
dp[rows - 1][j] = dp[rows - 2][j - 1] + lastLine.get(j);
min = Math.min(min, dp[rows - 1][j]);
return min;
}
}

Follow Up

Using only O(n) extra space, where n is the total number of rows in the triangle

  • This problem assumes that the triangle is from 1(top) to n(bottom), so the follow up actually means the length of the bottom row rather than the number of rows.

solution

  • Can keep a 1d-array which contains current line minimum number as the previous count will never be used again.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Solution {
public int minimumTotal(List<List<Integer>> triangle) {
int rows = triangle.size();
int length = triangle.get(rows - 1).size();
int[] dp = new int[length + 1];
for (int i = rows - 1; i >= 0; i--) {
List<Integer> line = triangle.get(i);
for (int j = 0; j < line.size(); j++) {
dp[j] = Math.min(dp[j], dp[j + 1]) + line.get(j);
}
}
return dp[0];
}
}