首页 > 其他 > 详细

leetcode ---Unique Paths

时间:2016-02-24 22:47:41      阅读:269      评论:0      收藏:0      [点我收藏+]

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?

(二维图像,只能往右或下走一步,从左上角到右下角一共多少种走法?)

方法一:确定到任意一个点能有多少种走法?

当x=0或y=0时,只能有一种;

当x!=0 且 y!=0时,有 matrix[y][x]=matrix[y-1][x] + matrix[y][x-1]种走法;用   (上+左)

代码:

public class Solution {
   int[][] matrix;
public int uniquePaths(int m, int n) {
    matrix = new int[n][m];
    for(int y=0; y<n; y++) {
        for(int x=0; x<m; x++) {
            //Fill top row and left most row with 1s
            if(x == 0 || y==0) matrix[y][x]=1;
            else {
                matrix[y][x]=matrix[y-1][x] + matrix[y][x-1];                   //相当于把每个点的走法种类都表示出来
            }
        }
    }
    return matrix[n-1][m-1];        //返回的时候要注意,不要越界
}
}

leetcode ---Unique Paths

原文:http://www.cnblogs.com/neversayno/p/5215334.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!