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).

62. Unique Paths_第1张图片

How many possible unique paths are there?

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

Note: m and n will be at most 100.

分析

动态规划

要想到到finish,要么到达 h1,要么到达 h2,因此要想求到达finish的不同路径,即是求解到达h1或h2的所有路径。

边界情况:
要想到达h1的上方那个框,只能有一种方式;
要想到达start下的下方那个框,也只有一种方式;

62. Unique Paths_第2张图片

因此状态转移方程为:

state transition equation:
dp[i][j] = dp[i-1][j] + dp[i][j-1]

boundary:
dp[0][j]=1;
dp[i][0]=1

代码实现

public class Solution {
     //state transition equation:
        //dp[i][j] = dp[i-1][j]+dp[i][j-1]
        //boundary: dp[0][j]=1; dp[i][0]=1
        public int UniquePaths(int m, int n)
        {
            int[,] dp = new int[m,n];
            //two boundaries:
            for (int i = 0; i < m; i++)
                dp[i,0] = 1;
            for (int i = 0; i < n; i++)
                dp[0,i] = 1;
            //dp[i][j] = dp[i-1][j]+dp[i][j-1]
            for (int i = 1; i < m; i++)
            {
                for (int j = 1; j < n; j++)
                {
                    dp[i, j] = dp[i - 1, j] + dp[i, j - 1];
                }
            }
            return dp[m - 1, n - 1];
        }
}

你可能感兴趣的:(算法/LeetCode,经典算法,LeetCode题目研究)