LeetCode 62. Unique Paths

题目:机器人位于网格的左上角(下图中标记为“Start”)并试图到达网格的右下角(下图中标记为“Finish”)。机器人只能在任何时间点向下或向右移动。有多少种可能的路径?A robot is located at the top-left corner of amxngrid (marked 'Start' in the diagram below).The robo...
摘要由CSDN通过智能技术生成

题目:

机器人位于网格的左上角(下图中标记为“Start”)并试图到达网格的右下角(下图中标记为“Finish”)。

机器人只能在任何时间点向下或向右移动。

有多少种可能的路径?

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 7 x 3 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

Input: m = 3, n = 2          Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Input: m = 7, n = 3          Output: 28

思路:

从终点开始,依次往上/往左计算该格子到终点的路径数——因为每个格子只能走两个位置,即右和下,所以【每个位置到终点的路径数】 = 【其下格到终点路径数】 + 【其右格到终点路径数】

用一个与m×n相同大小的二维数组来存储每个位置到终点的路径数,最后返回matrix[0][0]的结果

初始化时,由于每个位置不能往上走,因此最下面一行都为1;又由于每个位置不能往左走,因此最右一列都为1,再依次往左上角计算,每次计算是按斜线的格子计算,如下图:

 

代码: 

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] path = new int[m][n];
        for(int i=0;i<n;i++) {
            path[m-1][i]=1;
        }
        
        for(int i=0;i<m;i++) {
            path[i][n-1]=1;
        }
        update(path,m-2,n-2);
        return path[0][0];
    }
    
    public void update(int[][] path,int m,int n) {
        int count = m+n;	
        for(int i=count;i>=0;i--) {
            for(int j=i;j>=0;j--) {
                if(j<=m && i-j<=n) {				
                    path[j][i-j] = path[j+1][i-j] + path[j][i-j+1];
                }
            }
        }
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值