Leetcode_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.


两种方法,做出来结果都是4ms。第一种是打表,第二种是直接算C(m+n-2,n-1)。但第二种的复杂度从时间和空间上来讲都更优一些吧。

方法一:如果用table[m][n]表示结果,那么table[m][n]=table[m-1][n]+table[m][n-1]是很容易想到的。用递归的方法也小实验了一下,递归树太大,无可争议的TLE。所以想到用打表的方法来做。时间和空间复杂度均为O(m*n)。

class Solution {
public:
    int table[101][101];
    int uniquePaths(int m, int n) {
        for(int i=1;i<=m;++i){
            for(int j=1;j<=n;++j){
                if(i==1||j==1){
                    table[i][j] = 1;
                }
                else{
                    table[i][j] = table[i-1][j]+table[i][j-1];
                }
            }
        }
        return table[m][n];
        
    }
};

方法二:走的步数一共是m+n-2次,从里面选出m-1次向下的和n-1次向上的就行了。所以C(m+n-2,n-1)就可以。麻烦的是算起来容易溢出。之前编程的时候遇到过类似的问题,找到了一个可以大概避免溢出的小办法。就是一边乘一边除。时间复杂度降低到O(m+n),空间复杂度降低到O(1)

class Solution {
public:

    int uniquePaths(int m, int n) {
        //C(m+n-2,n-1)
        int max = m>n? m-1 : n-1;
        int min = m+n-2-max;
        unsigned long long res = 1;
        int little=2;
        for(int k=max+1;k<=m+n-2;++k){
            res*=k;
            while(res%little==0&&little<=min){
                res/=little;
                little++;
            }
        }
        return (int)res;
    }
};


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值