Unique Paths && Unique Paths|| 尾递归的简化,数学排列组合,动态规划

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?


Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

这道题有三种解法

1.递归算法(暴力)

机器人每次只有两种选择,即向右或向下,所以当前位置的路径条数等于向右一步和向下一步的路径和。

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

     显而易见,Leetcode 没有AC这种解法,因为 Time Exceed

2.简化的递归算法(或者动态规划)

尾递归都可以通过建立数组存储之前的值来避免,此处可以建立一个m * n的二维数组,每个位置的值是从起点到达这个位置的路径条数空间复杂度为O(m*n)时间复杂度为O(m * n)

class Solution {
    public int uniquePaths(int m, int n) {
        int[][] arr = new int[m][n];
        for(int i = 0;i < m;i ++)
            arr[i][0] = 1;
        for(int i = 0;i < n;i ++)
            arr[0][i] = 1;
        for(int i = 1;i < m;i ++)
            for(int j = 1;j < n;j ++)
                arr[i][j] = arr[i - 1][j] + arr[i][j - 1];
        return arr[m - 1][n - 1];
    }
}

 动态规划(dp)的想法是:建一个一维数组来存储当前行的路径条数,通过行与行之间的递推关系来解决问题。


public class Solution {
    public int uniquePaths(int m, int n) {
        if(m <= 0 || n <= 0)
            return 0;
        int[] res = new int[n];
        res[0] = 1;
        for(int i = 0; i < m; i ++) {
            for(int j = 1; j < n; j ++) {
                res[j] = res[j] + res[j - 1];
            }
        }
        return res[n - 1];
    }
}

3.纯数学算法(排列组合)

对于机器人来说,总的步数是固定的,向下走向右走的步数也是固定的。唯一不同的就是向下和向右步数的顺序问题。用组合数公式即可求解(代码就不写了)注意n和m用到组合数中应该减一。

组合数公式:c(m,n) = m! / (n! * (m - n)!)


Unique Paths ||

主要是加了障碍物,导致第三种算法失灵。动态规划仍可求解,只要注意障碍物位置和附近位置的关系即可。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值