[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 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

解法一:

recursion的方法。base case是走到最左边或者最底边,就只剩一条path了。不过OJ有runtime error了。

class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m==1) return 1;
        if(n==1) return 1;
        
        return uniquePaths(m-1,n)+uniquePaths(m,n-1);
    }
};


解法二:

dp的方法,其实上面公式很明显了,dp的公式就是dp[i][j] = dp[i][j-1]+dp[i-1][j],然后可以只用一个数组来实现。

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector dp(n);
        dp[0] = 1;
        
        for(int i=0; i

解法三:

直接用排列组合的方法。机器人一共要走m+n-2步,而要想下走m-1步。这里还要考虑m-1和n-1谁小的问题。

class Solution {
public:
    int uniquePaths(int m, int n) {
        int step = m+n-2;
        int num = m



你可能感兴趣的:(leetcode)