Leetcode028--唯一路径

来源:互联网 发布:四维设计软件 编辑:程序博客网 时间:2024/06/05 18:48

一、原题



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][n];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-------------------------

12620



1 0
原创粉丝点击