您的位置:首页 > 编程语言 > Java开发

Leetcode028--唯一路径

2017-01-31 15:59 246 查看
一、原题



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. 

一、中文

一个机器人在一个m*n的方格的左上角。 

机器人只能向右或都向下走一个方格,机器人要到达右下角的方格。 

请问一共有多少种唯一的路径。 
注意:m和n最大不超100。 






三、举例

矩阵中含有就返回true,如果矩阵中没有就返回false


四、思路

 

1、当x=0或者y=0时有A[x][y] = 1; 

2、当x>=1并且y>=1时有A[\x][\y] = A[x-1][y]+A[\x][y-1]。 

3、所求的结点就是A[m-1][n-1]。

动态规划的问题,是牺牲空间换区时间的一种方式,需要一个边界条件,一个递归的方式


五、程序

 
3、所求的结点就是A[m-1][n-1]。

package code;

public class LeetCode38{

public static void main(String args[]){
System.out.println(uniquePathNum(1, 1));
System.out.println(uniquePathNum(2, 2));
System.out.println(uniquePathNum(3, 3));
System.out.println(uniquePathNum(4, 4));
}

//一共有多少种不同的路径
public static int uniquePathNum(int m, int n) {
int res[][] = new int[m]
;

for(int i = 0; i < m; i++){
res[i][0] = 1;
}

for(int j = 0; j < n; j++){
res[0][j] = 1;
}

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

return res[m - 1][n - 1];
}

}


--------------------------output-------------------------

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