算法:唯一路径Unique Paths 动态规划和二项系数解法

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?

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

在这里插入图片描述

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:

  1. Right -> Right -> Down
  2. Right -> Down -> Right
  3. Down -> Right -> Right

Example 2:

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

Constraints:

1 <= m, n <= 100

It’s guaranteed that the answer will be less than or equal to 2 * 10 ^ 9.

1 动态规划解法

动态规划主要是找到跟上一条记录联系的公式,这里的公式就是path[i][j] = path[i-1][j] + path[i][j-1]。可以看下面的图,

  1. 往下走的列path[i][0]都初始化为1,表示一直往下有一种的解法;往右走的行path[0][j]都初始化为1,表示一直往右有一种的解法。

  2. 再看第二列,当前位置的记录是由上面的解法,和左边的解法,加起来就是当前的解法。所以 2 = 1 + 1, 3 = 2 + 1. 以此类推。

  3. 结果是path[m-1][n-1], 因为是从0开始计算的。
    在这里插入图片描述

public int uniquePaths(int m, int n) {
    int[][] dp = new int[m][n];
    for (int i = 0 ; i < m; i++) {
      dp[i][0] = 1;
    }
    for (int k = 0; k < n; k++) {
      dp[0][k] = 1;
    }
    for (int i = 1; i < m; i++) {
      for (int k = 1; k < n; k++) {
        dp[i][k] = dp[i - 1][k] + dp[i][k - 1];
      }
    }return dp[m - 1][n - 1];
  }

2 二项系数解法Binomial coefficient

数学公式的解法,实际上先考虑一共要走多少步。比如Input: m = 7, n = 3,实际上是 m- 1 + n -1, 也就是8步。这就是表示有8个空要等着填。那么有多少种填发呢,比如往下走表示D,往右走表示R,因为二项系数解法,大小都是一样的,为了效率,用小的来解比较快。比如有2个R, 由于 (n - 1)。那么第一个R可以放任意8个位置中的一个,第二个R可以放任意7个位置中的一个。因为左边(1, 2)和 (2, 1),都是放R的话是一样的,所以就要除以二项系数的当前系数。

在这里插入图片描述

class Solution {
    public int uniquePaths(int m, int n) {
        int totalStep = m + n - 2;
        int change = (m > n ? n : m) - 1;
        double count = 1;
        for (int i = 1; i <= change; i++) {
          count = count * totalStep / i;
          totalStep--;
        }return (int)count;
    }
}

参考

https://www.youtube.com/watch?v=M8BYckxI8_U

https://leetcode.com/problems/unique-paths/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值