LeetCode 62. Unique Paths

题目链接:https://leetcode.com/problems/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.


解题思路:

动态规划方法:用一个大小为m * n的二维数组Path代表整个diagram,其中Path[m-1][n-1] 表示从Start到Finish的unique paths数量。 那么到达[m-1][n-1]的上一个位置只可能是[m-2][n-1]或者[m-1][n-2]。 因此可以得到最关键的信息: Path[m-1][n-1]  = Path[m-2][n-1] + Path[m-1][n-2]. 以及初始化时的 Path[i][0] =  Path[0][j] = 1.

代码实现:

使用递归(未通过LeetCode测试,出现Time Limit Exceeded错误)

public class Solution {
    public int uniquePaths(int m, int n) {
        if ((m == 1 )||(n == 1)){
            return 1;
        }else{
            return uniquePaths(m-1, n) + uniquePaths(m, n-1);
        }
    }
}

不使用递归(通过LeetCode测试):

public class Solution {
    public int uniquePaths(int m, int n) {
        int [][] array = new int[m][n];
        for (int i=0;i
   
   


原因分析:
递归方法和非递归方法的计算结果是一致的,但是递归方法使用的时间远远大于非递归方法,所以没有通过LeetCode测试,下面它们运行时间的比较:

diagram大小:   非递归时间          |            递归时间

[15][0]:                 0ms                 |                 0ms
[15][1]:                 0ms                 |                 0ms
[15][2]:                 0ms                 |                 0ms
[15][3]:                 0ms                 |                 0ms
[15][4]:                 0ms                 |                 0ms
[15][5]:                 0ms                 |                 0ms
[15][6]:                 0ms                 |                 0ms
[15][7]:                 0ms                 |                 0ms
[15][8]:                 0ms                 |                 0ms
[15][9]:                 0ms                 |                 19ms
[15][10]:                 0ms                 |                 29ms
[15][11]:                 0ms                 |                 52ms
[15][12]:                 0ms                 |                 157ms
[15][13]:                 0ms                 |                 250ms
[15][14]:                 0ms                 |                 696ms

[15][15]:                 0ms                 |                 1077ms

可以看出,随着diagram增大,时间差距越来越大。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值