#62 Unique Paths

Description

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?
在这里插入图片描述
Constraints:
1 <= m, n <= 100
It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

Examples

Example 1:

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:
Right -> Right -> Down
Right -> Down -> Right
Down -> Right -> Right

Example 2:

Input: m = 7, n = 3
Output: 28

解题思路

首先需要明确,这里的机器人行走方式只有两种,就是向右或者向下
这就意味着不用盘向下又回上去的情况,也就是说,对于一个3*3的图,可以分割为两个2*3的图,而不用考虑被割裂的两条1*3

那么按照这个思路,我首先想到的是递归

class Solution {
    public int time(int m, int n){
        if(m == 1 || n == 1)
            return 1;
        if(m == 2 && n == 2)
            return 2;
        int a, b;
        a = time(m - 1, n);
        b = time(m, n - 1);
        return a + b;
    }
    public int uniquePaths(int m, int n) {
        return time(m, n);
    }
}

这套代码很好理解,就不加赘述了,但这种递归会爆栈

后来一想,这不就是个动态规划吗

行/列1234567
11111111
211+1=22+1=31+3=41+4=51+5=61+6=7
311+2=33+3=64+6=1010+5=1515+6=2121+7=28
411+3=44+6=1010+10=2020+15=3521+35=5628+56=84

那初始化就是
n u m [ i ] [ 0 ] = 0 num[i][0] = 0 num[i][0]=0
n u m [ 0 ] [ i ] = 0 num[0][i] = 0 num[0][i]=0
递归公式就是
n u m [ i ] [ j ] = n u m [ i − 1 ] [ j ] + n u m [ i ] [ j − 1 ] num[i][j] = num[i-1][j] + num[i][j-1] num[i][j]=num[i1][j]+num[i][j1]

代码

这里就放动态规划的了

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] answer = new int[m][n];
        int i, j;
        for(i = 0; i < n; i++){
            answer[0][i] = 1;
        }
        
        for(i = 0; i < m; i++){
            answer[i][0] = 1;
        }
        
        for(i = 1; i < m; i++){
            for(j = 1; j < n; j++){
                answer[i][j] = answer[i - 1][j] + answer[i][j - 1];
            }
        }
        
        return answer[m - 1][n - 1];
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值