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?
递归回溯都有计算重复
子问题重叠所以用动态规划
依次计算从右到左的红线上的方格
但是实现起来好麻烦 走的很迂回
这样就很方便了
public int uniquePaths(int m, int n) {// 4 6
int[][] dp = new int[m][n];
int i,j;
for(int index = m*n-1;index >= 0;index--){
i = index / n;
j = index % n;
if(index == m*n-1) dp[i][j] = 1;
else{
dp[i][j] = 0;
if(i+1 < m) dp[i][j] += dp[i+1][j];
if(j+1 < n) dp[i][j] += dp[i][j+1];
}
}
for(i = 0;i < m;i++){
for(j = 0;j < n;j++)
System.out.printf("%4d",dp[i][j]);
System.out.println();
}
return dp[0][0];
}