leetcode——Climbing Stairs

来源:互联网 发布:nba2k罗德曼数据 编辑:程序博客网 时间:2024/05/29 06:45

原题目:

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?

解析:若n=1则只有一种方法,n=2则有2种方法,当n>=3,时,到第n阶的方法数等于到第n-1阶与到第n-2阶的方法数之和。显然,这是一个斐波那契数列,由此关系式,通过迭代可以在O(n)复杂度内求解(递归超时)。

class Solution {public:int climbStairs(int n) {if(n==1)return 1;else if(n==2)return 2; else{int c = 3, c1 = 2, t;for(int i=4; i<=n; i++){t = c;c = c + c1;c1 = t;}return c;}}};


0 0
原创粉丝点击