Leetcode 动态规划-62. Unique Paths

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/owenfy/article/details/86565486

给一个m×n的方格,只能向右或者向下,有多少走法

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

解法1:O(n^2)

path[i][j] = path[i-1][j] + path[i][j-1]

# include<bits/stdc++.h>
using namespace std;

int uniquePaths(int m,int n)
{
        vector<vector<int>> paths(m,vector<int>(n,1));
        for(int i = 1;i<m;i++){
                for(int j = 1;j<n;j++){
                        paths[i][j] = paths[i-1][j] + paths[i][j-1];
                }

        }

        return paths[m-1][n-1];
}
int main()
{
        int m,n;
        while(cin>>m>>n){
                int result = uniquePaths(m,n);
                cout<<result<<endl;
        }
}

其他解法日后补充

猜你喜欢

转载自blog.csdn.net/owenfy/article/details/86565486