62. Unique Paths

Question:

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.

此题首先想到数学方法即排列组合,如示例所示,可以将横着走每部之间可以插入竖着走的排列组合,首先3*7的矩阵,竖着走即可向下走的地方为7处,每处可能走0-2步,情况分为:

    1、连着走两步即 总共有7种

    2、先走一步再走一步,计算方法为选向下走时的的y坐标 即6(在y=1时向下走) +5+。。。+1 = 21

共28种

但当向下走的总步数多时情况复杂多比如3步数分为1,2;2,1;3;1,1,1;因此考虑递归方法

第一种递归为将子递归分为从第二行开始为起点,即3*7矩阵的话从第二行开始共有7个起点(7乘以2*7矩阵的步数)以此类推

代码为:

int uniquePaths(int m, int n) {
    if(m==1 || n==1) return 1;
    int s = 0;
    while(n--)
        s += uniquePaths(m-1,n+1) ;
    return s;
}

第二种递归为
:因每个起点只有两个初始出发点即(2,7)和(3,6)

int uniquePaths(int m, int n) {
    if(m==1 || n==1) return 1;
    return uniquePaths(m-1,n) + uniquePaths(m,n-1);
}

第二种更为简洁,但两份代码均未通过,当矩阵大于15后运算时间大于1s,因此声明静态局部变量,将已经运算后的结果储存避免多次计算:

int uniquePaths(int m, int n) {
    static int a[100][100] = {0};
    if(m==1 || n==1) return 1;
    if(a[m-1][n-1] != 0) return a[m-1][n-1];
    a[m-1][n-1] = uniquePaths(m-1,n) + uniquePaths(m,n-1);
    return a[m-1][n-1];
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值