File tree Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Expand file tree Collapse file tree 2 files changed +70
-0
lines changed Original file line number Diff line number Diff line change @@ -118,3 +118,4 @@ mod n0114_flatten_binary_tree_to_linked_list;
118118mod n0115_distinct_subsequences;
119119mod n0118_pascals_triangle;
120120mod n0119_pascals_triangle_ii;
121+ mod n0120_triangle;
Original file line number Diff line number Diff line change 1+ /**
2+ * [120] Triangle
3+ *
4+ * Given a triangle, find the minimum path sum from top to bottom. Each step you may move to adjacent numbers on the row below.
5+ *
6+ * For example, given the following triangle
7+ *
8+ *
9+ * [
10+ * [2],
11+ * [3,4],
12+ * [6,5,7],
13+ * [4,1,8,3]
14+ * ]
15+ *
16+ *
17+ * The minimum path sum from top to bottom is 11 (i.e., 2 + 3 + 5 + 1 = 11).
18+ *
19+ * Note:
20+ *
21+ * Bonus point if you are able to do this using only O(n) extra space, where n is the total number of rows in the triangle.
22+ *
23+ */
24+ pub struct Solution { }
25+
26+ // submission codes start here
27+
28+ impl Solution {
29+ pub fn minimum_total ( triangle : Vec < Vec < i32 > > ) -> i32 {
30+ let mut cache = vec ! [ 0 ; triangle. len( ) ] ;
31+ for row in triangle. iter ( ) {
32+ let mut prev = 0 ;
33+ for i in 0 ..row. len ( ) {
34+ let temp = cache[ i] ;
35+ cache[ i] = if i == 0 {
36+ cache[ i]
37+ } else if i == row. len ( ) - 1 {
38+ prev
39+ } else {
40+ i32:: min ( cache[ i] , prev)
41+ } + row[ i] ;
42+ prev = temp;
43+ }
44+ }
45+ cache. into_iter ( ) . fold ( i32:: max_value ( ) , |min, x| i32:: min ( min, x) )
46+ }
47+ }
48+
49+ // submission codes end
50+
51+ #[ cfg( test) ]
52+ mod tests {
53+ use super :: * ;
54+
55+ #[ test]
56+ fn test_120 ( ) {
57+ assert_eq ! (
58+ Solution :: minimum_total(
59+ vec![
60+ vec![ 2 ] ,
61+ vec![ 3 , 4 ] ,
62+ vec![ 6 , 5 , 7 ] ,
63+ vec![ 4 , 1 , 8 , 3 ]
64+ ]
65+ ) ,
66+ 11
67+ )
68+ }
69+ }
You can’t perform that action at this time.
0 commit comments