[LeetCode]70. Climbing Stairs

来源:互联网 发布:数据与安全监察委员会 编辑:程序博客网 时间:2024/06/11 21:08

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?

Note: Given n will be a positive integer.

1、递归。超时。

public class Solution {    public int climbStairs(int n) {        //f(n)=f(n-1)+f(n-2)        if(n==1) return 1;        else if(n==2) return 2;        else return climbStairs(n-1)+climbStairs(n-2);    }}


2、迭代

public class Solution {    public int climbStairs(int n) {        //f(n)=f(n-1)+f(n-2)        if(n==1) return 1;        else if(n==2) return 2;                int n1,n2,res;        n1=1; n2=2;        for(int i=3;i<n+1;i++){            res=n1+n2;            n1=n2;            n2=res;        }                return res;    }}


原创粉丝点击