Dynamic Programming - 62. Unique Paths

62. Unique Paths

A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).

The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).

How many possible unique paths are there?

Above is a 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Example 1:

Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:

1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28

（可以在维度上优化为一维，状态转移方程变成`dp[i] = dp[i-1] + dp[i]`，从左往右扫或者从上往下扫。以从上往下扫为例，当前dp[i]代表的就变成了走到dp[i]需要从左边往右走一步，也就时dp[i-1]，和上一层的第i列那个格子往下走一步，也就是上一个dp[i]）

go：

``````/*func uniquePaths(m int, n int) int {

if m <= 0 || n <= 0 {return 0}

// initial dp array
dp := make([][]int, m)
for i := 0; i < len(dp); i++ {
dp[i] = make([]int, n)
}

// find unique path
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if i == 0 || j == 0 { // initialization
dp[i][j] = 1
} else {
dp[i][j] = dp[i][j-1] + dp[i-1][j]
}
}
}

return dp[m-1][n-1]
}*/

func uniquePaths(m int, n int) int {
if m <= 0 || n <= 0  {
return 0
}

dp := make([]int, n)

// find unique path
for i := 0; i < m; i++ {
for j := 0; j < n; j++ {
if j == 0 {  // initialization
dp[j] = 1
} else {
dp[j] = dp[j] + dp[j-1]
}
}
}

return dp[n-1]
}```
``````

Nothing just happens, it's all part of a plan.