算法设计Week12 LeetCode Algorithms Problem #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?

 3 x 7 grid

Note: m and n will be at most 100.


题目分析:

我们可以用count[i][j]来表示到第i行第j列的空格上一共有多少种走法,经过分析,会有下式关系:
count[i][j] = count[i - 1][j] + count[j][i - 1]
有了递推关系,就可以很容易地实现本题的解了:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<vector<int>> count(m,vector<int>(n,1));
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                count[i][j] = count[i - 1][j] + count[i][j - 1];
            }
        }
        return count[m - 1][n - 1];
    }
};

上面的解法时间复杂度为 O(mn) ,空间复杂度为 O(mn) 。但其实上面的解法只涉及到两行,因此,可以简化上述算法的空间复杂度至 O(n)

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<int> count1(n, 1);
        vector<int> count2(n, 1);
        for(int i = 1; i < m; i++){
            if(i % 2){
                add(count2, count1);
            }else{
                add(count1, count2);
            }
        }
        return max(count1[n - 1], count2[n - 1]);
    }
    void add(vector<int>& counta, vector<int>& countb){
        for(int i = 1; i < counta.size(); i++){
            counta[i] = counta[i - 1] + countb[i];
        }
    }
};

再仔细查看上面代码,可以注意到实际上可以使用一个数组来完成任务,从而更简化代码:

class Solution {
public:
    int uniquePaths(int m, int n) {
        vector<int> count(n, 1);
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                count[j] = count[j - 1] + count[j];
            }
        }
        return count[n - 1];
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值