1. 程式人生 > >LeetCode-62 Unique Paths

LeetCode-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[0][0] 賦值1後面的迭代就好了.

solution:

class Solution {
    public int uniquePaths(int m, int n) {
        if(m==0||n==0) //如果m==0或者n==0直接返回0就可以了因為這樣的二維陣列沒有意義
            return 0;
        int[][] dp = new int[m+1][n+1]; 
        dp[0][0] = 1; //初始化動態規劃陣列
        for(int i=0;i<m;i++){
            for(int j=0;j<n;j++){
                if(i==0&&j>0) 
                    dp[i][j]+=dp[i][j-1]; //如果是第一行那麼它只能是往右走得來的不能是往下走得來的
                else if(j==0&&i>0)  
                    dp[i][j]+=dp[i-1][j]; //如果是第一列那麼它只能是往下走得來的不能是往右走得來的
                else if(i!=0&&j!=0)  //其它情況即可以由往右走得來也可以由往下走得來
                    dp[i][j] +=(dp[i-1][j]+dp[i][j-1]);
            }
        }
        return dp[m-1][n-1]; //返回答案
    }
}