您的位置:首页 > 产品设计 > UI/UE

Unique Paths

2015-07-13 10:05 471 查看
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.

思路:robot要么向下走,要么向下走,求总共的次数,就应该是向右走之后和向下走之后的次数的总和,这个问题和青蛙跳台阶很类似,可以转化为递归,但是递归超时了,一样的,同青蛙跳台阶一样,将递归转化为迭代。

public int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0)
return 0;
return paths(m, n, 1, 1);

}

public int paths(int m, int n, int right, int down) {
if (right == n && down < m)
return 1;
if (right < n && down == m)
return 1;
return paths(m, n, right + 1, down) + paths(m, n, right, down + 1);

}


迭代: 可以把机器人当作终点,星星当作起点,a[i][j]表示的是第i行和第j列时到终点的总的路径数,那么就有a[i][j] = a[i - 1][j] + a[i][j - 1];

初始化条件 ,最后a[m-1][n-1]的值即为所求。

a[i][0] = 1; i从1到n-1

a[0][j] = 1; j 从1到m-1

public class Solution {
public int uniquePaths(int m, int n) {
if (m <= 0 || n <= 0)
return 0;
if(m==1||n==1) return 1;
int[][] a = new int[m]
;
a[0][0] = 0;
for (int i = 1; i <= m - 1; i++)
a[i][0] = 1;
for (int j = 1; j <= n - 1; j++)
a[0][j] = 1;

for (int i = 1; i <= m - 1; i++) {
for (int j = 1; j <= n - 1; j++) {
a[i][j] = a[i - 1][j] + a[i][j - 1];
}
}

return a[m - 1][n - 1];

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: