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

Unique path

2015-09-23 11:26 453 查看
题目:

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)
{
int [][] grids = new int [m+1][n+1];
grids[m][n-1]=1;
for (int i=m-1;i>=0;i--)
{
for (int j=n-1;j>=0;j--)
{
grids[i][j]=grids[i+1][j]+grids[i][j+1];

}
}
return grids[0][0];
}


解法二:九章算法,好理解

public class Solution {
public int uniquePaths(int m, int n) {
if (m == 0 || n == 0) {
return 0;
}

int[][] sum = new int[m]
;
for (int i = 0; i < m; i++) {
sum[i][0] = 1;
}
for (int i = 0; i < n; i++) {
sum[0][i] = 1;
}
for (int i = 1; i < m; i++) {
for (int j = 1; j < n; j++) {
sum[i][j] = sum[i - 1][j] + sum[i][j - 1];
}
}
return sum[m - 1][n - 1];
}
}


reference:http://www.jiuzhang.com/solutions/unique-paths/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: