Skip to content

Commit 5ec62c5

Browse files
committed
added problem 64
1 parent eead9c4 commit 5ec62c5

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

problems/problem0064/min_path_sum.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package problem0064
2+
3+
import "math"
4+
5+
/*
6+
Given a m x n grid filled with non-negative numbers,
7+
find a path from top left to bottom right, which minimizes the sum of all numbers along its path.
8+
Note: You can only move either down or right at any point in time.
9+
*/
10+
11+
func minPathSum(grid [][]int) int {
12+
for i := len(grid) - 1; i >= 0; i-- {
13+
for j := len(grid[0]) - 1; j >= 0; j-- {
14+
if i == len(grid)-1 && j == len(grid[0])-1 {
15+
continue
16+
}
17+
var r, d int = math.MaxInt, math.MaxInt
18+
if i+1 < len(grid) {
19+
r = grid[i+1][j]
20+
}
21+
if j+1 < len(grid[0]) {
22+
d = grid[i][j+1]
23+
}
24+
grid[i][j] += min(r, d)
25+
}
26+
}
27+
return grid[0][0]
28+
}
29+
30+
func min(a, b int) int {
31+
if a < b {
32+
return a
33+
}
34+
return b
35+
}
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package problem0064
2+
3+
import (
4+
"fmt"
5+
"testing"
6+
7+
"github.com/stretchr/testify/assert"
8+
)
9+
10+
type Result struct {
11+
Input [][]int
12+
Expected int
13+
}
14+
15+
var Results = []Result{
16+
{[][]int{
17+
{1, 3, 1},
18+
{1, 5, 1},
19+
{4, 2, 1},
20+
}, 7},
21+
{[][]int{
22+
{1, 2, 3},
23+
{4, 5, 6},
24+
}, 12},
25+
}
26+
27+
func TestMinPathSum(t *testing.T) {
28+
assert := assert.New(t)
29+
30+
for _, res := range Results {
31+
want := res.Expected
32+
got := minPathSum(res.Input)
33+
assert.Equal(want, got, fmt.Sprintf("%+v", res))
34+
}
35+
}

readme.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -63,6 +63,7 @@ Each problem is in it's own directory, with test files. There are helper package
6363
| 0059 | [Spiral Matrix II](https://leetcode.com/problems/spiral-matrix-ii) | [My Solution](./problems/problem0059) ||
6464
| 0062 | [Unique Paths](https://leetcode.com/problems/unique-paths) | [My Solution](./problems/problem0062) ||
6565
| 0063 | [Unique Paths II](https://leetcode.com/problems/unique-paths-ii) | [My Solution](./problems/problem0063) ||
66+
| 0064 | [Minimum Path Sum](https://leetcode.com/problems/minimum-path-sum) | [My Solution](./problems/problem0064) ||
6667
| 0066 | [Plus One](https://leetcode.com/problems/plus-one/) | [My Solution](./problems/problem0066) ||
6768
| 0067 | [Add Binary](https://leetcode.com/problems/add-binary) | [My Solution](./problems/problem0067) ||
6869
| 0069 | [Sqrt(x)](https://leetcode.com/problems/sqrtx) | [My Solution](./problems/problem0069) ||

0 commit comments

Comments
 (0)