【题目】
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 pZ??http://www.2cto.com/kf/ware/vc/" target="_blank" class="keylink">vc3NpYmxlIHVuaXF1ZSBwYXRocyBhcmUgdGhlcmU/PC9wPgo8cD4KTm90ZTogbSBhbmQgbiB3aWxsIGJlIGF0IG1vc3QgMTAwLjwvcD4KPGg0PqG+y7zCt6G/PC9oND4KPHA+yehzW2ldW2pdIM6qtNPG8LXjtb2jqGksaqOpzrvWw7SmtcTCt762yv2hozwvcD4KPHA+zai5/bfWzva1w7W9o7q12tK70NCjrLXa0rvB0La8zqoxPC9wPgo8cD61vcbky/vOu9bDtKajqGksaqOpo7q1vbTvzrvWw6OoaSxqo6nWu8TctNPJz8Pmu/LV39fzw+a5/cC0o6zS8rTLvva2qLW9zrvWw6OoaSxqo6m1xMK3vrbK/dPJtb2078nPw+bOu9bDo6hpLTEsaqOptcTCt762yv26zbW9tO/X88PmzrvWw6OoaSxqLTGjqbXEwre+tsv5vva2qLXEoaM8L3A+CjxwPte0zKzXqtLGt72zzKO6PC9wPgo8cD5zW2ldW2pdID0gc1tpLTFdW2pdICYjNDM7IHNbaV1bai0xXTwvcD4KPHA+yrG85Li01NO2yKO6TyhuXjIpICC/1bzkuLTU07bIo7pPKG5eMik8L3A+CjxoND6hvrT6wuuhvzwvaDQ+CjxwPjwvcD4KPHByZSBjbGFzcz0="brush:java;"> /*------------------------------------ * 日期:2015-02-03 * 作者:SJF0115 * 题目: 62.Unique Paths * 网址:https://oj.leetcode.com/problems/unique-paths/ * 结果:AC * 来源:LeetCode * 博客: ---------------------------------------*/ #include
#include
#include
#include
using namespace std; class Solution { public: int uniquePaths(int m, int n) { int s[m][n]; for(int i = 0;i < m;++i){ for(int j = 0;j < n;++j){ if(i == 0|| j == 0){ s[i][j] = 1; }//if else{ s[i][j] = s[i-1][j] + s[i][j-1]; }//esle }//for }//for return s[m-1][n-1]; } }; int main(){ Solution s; int m = 3; int n = 4; int result = s.uniquePaths(m,n); // 输出 cout<

【思路二】
使用空间轮转的思路,节省空间。
状态转移方程:
s[j] = s[j] + s[j-1]
时间复杂度:O(n^2) 空间复杂度:O(n)
【代码二】
/*------------------------------------
* 日期:2015-02-03
* 作者:SJF0115
* 题目: 62.Unique Paths
* 网址:https://oj.leetcode.com/problems/unique-paths/
* 结果:AC
* 来源:LeetCode
* 博客:
---------------------------------------*/
class Solution {
public:
int uniquePaths(int m, int n) {
int s[n];
// 第一行全为1
for(int i = 0;i < n;++i){
s[i] = 1;
}//for
// 从第二行开始
for(int i = 1;i < m;++i){
// 第i行第j个格
for(int j = 1;j < n;++j){
s[j] = s[j] + s[j-1];
}//for
}//for
return s[n-1];
}
};