LeetCode - Unique Paths - Frequent

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

第一眼看到这道题,就觉得该用递归做,递归解法如下:

public int uniquePaths(int m, int n) {
        int[] total = new int[1];
        helper(0, 0, total, m, n);
        return total[0];
    }
    public void helper(int row, int column, int[] total, int desti, int destj){
        if(row==desti && column==destj){
            total[0]++;
            return;
        }
        if(row>desti || column>destj) return;
        helper(row+1, column, total, desti, destj);
        helper(row, column+1, total, desti, destj);
    }


递归解法超时,发现其实可以用DP做:

    public int uniquePaths(int m, int n){
        int[][] paths = new int[m][n];
        paths[0][0]=1;
        for(int i=0; i<m; i++){
            for(int j=0; j<n; j++){
                if(i==0 && j==0) continue;
                else if(i==0) paths[i][j] = paths[i][j-1];
                else if(j==0) paths[i][j] = paths[i-1][j];
                else paths[i][j] = paths[i-1][j]+paths[i][j-1];
            }
        }
        return paths[m-1][n-1];
    }

后来看了大神的文章,发现其实一维数组就能解决,可以节省空间,但是时间复杂度是一样的,解法如下:
    public int uniquePaths(int m, int n){
        int[] paths = new int[n];
        paths[0] = 1;
        for(int i=0; i<m; i++){
            for(int j=1; j<n; j++){
                paths[j] = paths[j]+paths[j-1];
            }
        }
        return paths[n-1];
    }


本题最小空间复杂度是O(n),时间复杂度是O(m*n)

总结:在用递归时,都应该考虑是否能用DP解,并且,在DP时,要尽量减少空间复杂度。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值