[leetcode] 62.Unique Paths

题目:
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?
题意:机器人从左上角作为起点前往右下角的重点,每次只能往右移或者往下移。
思路:对于每个格点我们考虑机器人能够从哪些格点跳到该格点上。比如对于(0,1)这个位置即第一行第二列的位置,也就是机器人的起始位置的右一个位置,(0,1)只能由(0,0)往右跳一格到达,而对于(2,2)可以由(1,2)或者(2,1)跳达。第一行的格点只能由机器人往右跳到达,第一列的格点只能由机器人往下跳一格到达,其余的格点可以由机器人从左往右跳一格或者从上往下跳一格到达。思路到这儿就很明显了,这是一个动态规划的问题。

  1. DP[i][j] = 1(i == 0 || j == 0);
  2. DP[i][j] = DP[i-1][j] + DP[i][j-1];

参考以下代码:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值