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?
这里写图片描述
Above is a 3 x 7 grid. How many possible unique paths are there?

Note: m and n will be at most 100.

问题描述:

有一个7*3的格子,机器人从最左上角走到最右下角有多少种走法。机器人只能向下或者向右走,每次只能走一步。

解法一:

思路:

动态规划思路

找到子问题,机器人走到(i,j)处公园多少种走法,标记为map[i][j]。
要解决的目标是求得map[m-1][n-1]

状态转移方程:
map[i][j] = map[i-1][j] + map[i][j-1];

map[i][j] 为
从map[i-1][j]的所有走法中再向右移一步,
和map[i][j-1]的所有走法中再向下移一步
总步数之和。

Code:

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

        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                map[i][j] = map[i-1][j] + map[i][j-1];
            }
        }

        return map[m-1][n-1];
    }
}

解法二:

思路:

这里从宏观上把握这个问题,无论机器人怎么走,最后达到终点,都需要向右走m-1步,向下走n-1步,总步数为m+n-2步。
其实就是个排列组合问题,从总步数m+n-2步拿出m-1步向右走(或拿出n-1步向下走)有多少种方法?

Combination(N, k) = n! / (k!(n - k)!)
C = ( (n - k + 1) * (n - k + 2) * … * n ) / k!

基本的高中数学问题

Code:

public int uniquePaths(int m, int n) {
        int N = n + m - 2;
        int k = Math.min(m-1,n-1);
        double paths = 1;

        for(int i = 1; i <= k; i++){
            paths *= ((double)(N - k + i) / (double)i);
        }
        return (int)Math.round(paths);
    }

注意这里的小trick,为了降时间复杂度,选m-1和n-1的较小值作为循环体,再计算排列数时强制转换为double类型,最后返回路径数用Math.round()进行向上取整,并且强制转化为int型返回。

彩蛋:

解法一的空间复杂度还可以降,就如同之前讲的爬楼梯问题,可以用滚动数组将空间复杂度降到O(n),限于时间关系,没有列出。这里给读者思考。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值