70Climbing Stairs

来源:互联网 发布:centos jdk rpm 编辑:程序博客网 时间:2024/04/30 08:02

题目链接:https://leetcode.com/problems/climbing-stairs/

题目:

You are climbing a stair case. It takes n steps to reach to the top.Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

解题思路:
这题一眼就能看出可以用递归计算,可是,会超时。由于看过《剑指 Offer》,自然对这种题有新的思路,那就是斐波那契数列。
这题的递归求解式与斐波那契数列递推式一致,都是:
f(0) = f(1) = 1
f(n) = f(n - 1) + f(n - 2)
所以用一个 for 循环即可搞定。

代码实现:

public class Solution {    public int climbStairs(int n) {        if(n == 0 || n == 1)            return 1;        int res = 0;        int a = 1;        int b = 1;        for(int i = 2; i <= n; i ++) {            res = a + b;            a = b;            b = res;        }        return res;    }}
45 / 45 test cases passed.Status: AcceptedRuntime: 0 ms
0 0
原创粉丝点击