[算法分析与设计] leetcode 每周一题: 62. Unique Paths

题目链接: https://leetcode.com/problems/unique-paths/description/
题目大意:给定大小的网格,从左上顶点到右下顶点一共有多少不同的路径。(只允许向下和向右走)


思路:因为(a,b)到(m,n)的路径数 = (a+1,b)到(m,n)路径数+(a,b+1)到(m,n)的路径数(a+1 < m, b+1 < n),所以一开始本人打算暴力递归遍历所有的可能路径,代码如下:

class Solution {
public:
    int uniquePaths(int m, int n) {
        return getPath(1,1,m,n)
    }
    int getPath(int x, int y, int m, int n) {
    	if(x == m && y == n) return 1;
    	if(x > m || y > n) return 0;
    	return getPath(x+1, y, m, n) + getPath(x, y+1,m,n);
    }
};
结果超时,因此我查看了其他人的博客,发现了可以用动态规划来解决,同时动态规划因为缓存了子问题的解,因此不超时。在动态规划的解决方案中,
思路稍微和我递归的反了过来,(0,0)到(a,b)的路径数 = (0, 0)到 (a-1,b)路径数 +  (0,0) 到(a,b-1)路径数
代码如下:

class Solution {
public:
    int uniquePaths(int m, int n) {
        return getPath(1,1,m,n)
    }
    int getPath(int x, int y, int m, int n) {
    	if(x == m && y == n) return 1;
    	if(x > m || y > n) return 0;
    	return getPath(x+1, y, m, n) + getPath(x, y+1,m,n);
    }
};





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值