Skip to content

Commit 6102900

Browse files
committed
'Triangle' solns
1 parent bb1af83 commit 6102900

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

leetcode/triangle.rs

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
///
2+
/// Problem: Triangle
3+
///
4+
/// Given a triangle array, return the minimum path sum from top to bottom.
5+
///
6+
/// For each step, you may move to an adjacent number of the row below. More formally,
7+
/// if you are on index i on the current row, you may move to either index i or index i + 1
8+
/// on the next row.
9+
///
10+
/// Example 1:
11+
/// Input: triangle = [[2],[3,4],[6,5,7],[4,1,8,3]]
12+
/// Output: 11
13+
/// Explanation: The triangle looks like:
14+
/// 2
15+
/// 3 4
16+
/// 6 5 7
17+
/// 4 1 8 3
18+
/// The minimum path sum from top to bottom is 2 + 3 + 5 + 1 = 11.
19+
///
20+
/// Example 2:
21+
/// Input: triangle = [[-10]]
22+
/// Output: -10
23+
///
24+
/// Constraints:
25+
/// 1 <= triangle.length <= 200
26+
/// triangle[0].length == 1
27+
/// triangle[i].length == triangle[i - 1].length + 1
28+
/// -10^4 <= triangle[i][j] <= 10^4
29+
///
30+
/// Follow up: Could you do this using only O(n) extra space, where n is the total number
31+
/// of rows in the triangle?
32+
///
33+
34+
// # Solution 1
35+
// Time complexity: O(n²)
36+
// Space complexity: O(n²)
37+
38+
39+
impl Solution {
40+
pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 {
41+
let n = triangle.len();
42+
43+
let mut dp = vec![vec![0; n]; n];
44+
45+
for j in 0..n {
46+
dp[n - 1][j] = triangle[n - 1][j];
47+
}
48+
49+
for i in (0..n-1).rev() {
50+
for j in 0..=i {
51+
52+
dp[i][j] = triangle[i][j] + std::cmp::min(dp[i + 1][j], dp[i + 1][j + 1]);
53+
}
54+
}
55+
56+
dp[0][0]
57+
}
58+
}
59+
60+
61+
// # Solution 2:
62+
// Time complexity: O(n²)
63+
// Space complexity: O(n)
64+
65+
impl Solution {
66+
pub fn minimum_total(triangle: Vec<Vec<i32>>) -> i32 {
67+
let n = triangle.len();
68+
69+
let mut dp = triangle[n - 1].clone();
70+
71+
for i in (0..n-1).rev() {
72+
for j in 0..=i {
73+
74+
dp[j] = triangle[i][j] + std::cmp::min(dp[j], dp[j + 1]);
75+
}
76+
}
77+
78+
dp[0]
79+
}
80+
}

0 commit comments

Comments
 (0)