遞歸
int uniquePaths(int m, int n){
int move(int x, int y, int m, int n){
int n1 = 0;
int n2 = 0;
if( x == m && y == n){
return 1;
}
// 向右走,限制多餘的步數
if( x <= m){
n1 = move(x+1,y,m,n);
}
if( y <= n){
n2 = move(x,y+1,m,n);
}
return n1 + n2;
}
return move(0,0,m-1,n-1);
}
- 超出時間限制
動態規劃
int uniquePaths(int m, int n){
int dp[m][n];
int i,j;
for( i = 0; i < m; i++){
for( j = 0; j < n; j++){
dp[i][j] = 1;
}
}
for( i = 1; i < m; i++){
for( j = 1; j < n; j++){
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
return dp[m-1][n-1];
}
降低空間複雜度
- 利用楊輝三角形
int uniquePaths(int m, int n){
int cur[n];
int i,j;
for( i = 0; i < n; i++){
cur[i] = 1;
}
for( i = 1; i < m; i++){
for( j = 1; j < n; j++){
cur[j] += cur[j-1];
}
}
return cur[n-1];
}
參考
[1]代碼