[LeetCode] 62. Unique Paths(不同的路径)
- 
Difficulty: Medium 
- 
Related Topics: Array, Dynamic Programming 
Description
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
一只机器人位于 m x n 方格的左上角(下图中以“Start”标识)。
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).
机器人只能向下或向右移动。该机器人欲抵达方格的右下角(下图中以“Finish”标识)。
How many possible unique paths are there?
有多少种不同的路径?
Examples
Example 1

Input: m = 3, n = 7
Output: 28
Example 2
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 -> Down -> Down
2. Down -> Down -> Right
3. Down -> Right -> Down
Example 3
Input: m = 7, n = 3
Output: 28
Example 4
Input: m = 3, n = 3
Output: 6
Constraints
- 
1 <= m, n <= 100
- 
It's guarranteed that the answer will be less than or equal to 2 * 10^9.
Solution
动态规划例题之二,状态转义方程如下:
\[\texttt{dp(i, j)} = \begin{cases}
1, &i = 0 或j = 0\\
\texttt{dp(i - 1, j)} + \texttt{dp(i, j - 1)}, &else
\end{cases}
\]
其中 dp(i, j) 表示 (i, j) 时可能的路径数
class Solution {
    fun uniquePaths(m: Int, n: Int): Int {
        val dp = Array(m) { IntArray(n) }
        (0 until m).forEach { dp[it][0] = 1 }
        (0 until n).forEach { dp[0][it] = 1 }
        for (i in 1 until m) {
            for (j in 1 until n) {
                dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
            }
        }
        return dp.last().last()
    }
}

 
                
            
         浙公网安备 33010602011771号
浙公网安备 33010602011771号