您的位置:首页 > 编程语言 > Java开发

Climbing Stairs | leetcode 70 【Java解题报告】

2015-10-07 13:00 711 查看
原题链接:70. Climbing Stairs
【思路】

题目提示动态规划。我们知道第 n 阶只与第 n - 1 阶和 第 n - 2 阶有关,关系为ways
= ways[n - 1] + ways[n - 2],存储的时候只需要2个存储单元,本题用ways[0]存 n - 2 阶的走法数,ways[1]存储 n - 1 阶走法数:

public class Solution {
    public int climbStairs(int n) {
        int[] ways = {1, 1};
        for (int i = 1; i < n; i++) {
            int temp = ways[1];
            ways[1] += ways[0];
            ways[0] = temp;
        }
        return ways[1];
    }
}

45 / 45 test
cases passed. Runtime: 0
ms Your runtime beats 13.04% of javasubmissions.

【补充】

递归解法

public class Solution {
public int climbStairs(int n) {
if(n == 1 || n<=0) return 1;
return climbStairs(n-1) + climbStairs(n-2);       //Time Limit Exceeded when n >= 42
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: