leetcode【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

源码:

第一眼一看,这不和剑指offer中的剑指offer-机器人的运动范围有点像嘛,喀喀喀编完了,最后超时,我抑郁了。(超时代码如下)当找到最后一行或者最后一列的时候,我还自作聪明的做了一点优化。

class Solution {
public:
    int count = 0;
    int uniquePaths(int m, int n) {
        if(m<=1 || n<=1)    return 1;
        vector<bool> visit(m*n, false);
        moving(visit, 0, 0, m, n);
        return count;
    }
    
    void moving(vector<bool> &visit, int row, int col, int m, int n){
        if(row == m-1 && col == n-1){
            count++;    return;
        }
        if(row==m-1 || col==n-1){
            count++;
            return;
        }
        if(isvalid(visit, row, col, m, n)){
            visit[row*n+col] = true;
            moving(visit, row+1, col, m, n);
            moving(visit, row, col+1, m, n);
            visit[row*n+col] = false;
        }
    }
    
    bool isvalid(vector<bool> &visit, int row, int col, int m, int n){
        if(row<m && col<n && !visit[row*n+col]){
            return true;
        }
        return false;
    }
};

最后想想不对额,只能上下,不就是个简单的动态规划嘛,我更抑郁了!!!

class Solution {
public:
    int uniquePaths(int m, int n) {
        if(m<=1 || n<=1)    return 1;
        vector<vector<int>> count(m, vector<int> (n, 0));
        for(int i=0; i<m; i++)  count[i][0] = 1;
        for(int i=0; i<n; i++)  count[0][i] = 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];
    }
};

稍微优化一下,想做优化的话,考虑一下一维的count

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

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值