[LeetCode OJ]Climbing Stairs

来源:互联网 发布:太平洋电脑软件下载 编辑:程序博客网 时间:2024/05/01 02:30
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?


这英语够渣了现在……distinct歧义了半天= =直接导致刚开始没理解题意,后来明白了题意就简单了许多~

1----> 1
1阶楼梯的爬法总共为:1
2----> 1 1
2----> 2
2阶楼梯的爬法总共为:2
3----> 1 1 1
3----> 1 2
3----> 2 1
3----> 3
3阶楼梯的爬法总共为:4
4----> 1 1 1 1
4----> 1 1 2
4----> 1 2 1
4----> 1 3
4----> 2 1 1
4----> 2 2
4----> 3 1
4阶楼梯的爬法总共为:7
5----> 1 1 1 11
5----> 1 1 1 2
5----> 1 1 2 1
5----> 1 1 3
5----> 1 2 1 1
5----> 1 2 2
5----> 1 3 1
5----> 2 1 1 1
5----> 2 1 2
5----> 2 2 1
5----> 2 3
5----> 3 1 1
5----> 3 2
5阶楼梯的爬法总共为:13

利用迭代可以求解:

class Solution {public:    int climbStairs(int n) {        while(n == 1 || n == 0) {            return 1;        }        int pre = 1;        int current = 1;        int temp;        for(int i = 2; i <= n; i++) {            temp = pre + current;            pre = current;            current = temp;        }        return temp;    }};

0 0
原创粉丝点击