LeetCode70. Climbing Stairs(C++)

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.

Example 1:

Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps

Example 2:

Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step

解题思路:设爬n层楼梯有f(n)种方式,则爬n+1层楼梯有f(n+1)=f(n)+f(n-1);即分为两种情况,一种增加的这一层最后一步是一步爬上去的,该情况有f(n)种,第二种情况最后一层是在倒数第三层走了两步爬上去的,该情况有f(n-1)种。

class Solution {
public:
    int climbStairs(int n) {
        if(n==1||n==0)
            return 1;
        int x=1,y=1;
        for(int i=2;i

 

你可能感兴趣的:(Leetcode)