[leetcode_70]Climbing Stairs

Climbing stairs: you can either climb one step or two steps at a time. How many different ways can you climb to the top?

Using a search approach would result in TLE. So I switched to an iterative approach:
a[n] = a[n-1] + a[n-2]
Accepted on the first try.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
class Solution {
public:
    int climbStairs(int n) {
        // Note: The Solution object is instantiated only once and is reused by each test case.
        int a1 = 1;
        int a2 = 2;
        if(n == 1)
        {
            return a1;
        }
        if(n == 2)
        {
            return a2;
        }
        int index = 3;
        int before = a2;
        int now = a1 + a2;
        while(true)
        {
            if(index == n)
            {
                return now;
            }
            int tmp = before;
            before = now;
            now = tmp + before;
            index++;
        }
    }
};