diff options
Diffstat (limited to 'top-interview-questions/easy/dynamic_programming')
| -rw-r--r-- | top-interview-questions/easy/dynamic_programming/01_climbing_stairs.cc | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/top-interview-questions/easy/dynamic_programming/01_climbing_stairs.cc b/top-interview-questions/easy/dynamic_programming/01_climbing_stairs.cc new file mode 100644 index 0000000..19aa6a1 --- /dev/null +++ b/top-interview-questions/easy/dynamic_programming/01_climbing_stairs.cc | |||
| @@ -0,0 +1,22 @@ | |||
| 1 | class Solution { | ||
| 2 | public: | ||
| 3 | int climbStairs(int n) { | ||
| 4 | /* | ||
| 5 | ways(n-1, n) = 1 -- one step to n | ||
| 6 | ways(n-2, n) = 1 + 1 -- 1x two-step + 2x one-step | ||
| 7 | ways( k, n) = ways(k-1, n) + ways(k-2, n) | ||
| 8 | */ | ||
| 9 | if (n == 1) return 1; | ||
| 10 | if (n == 2) return 2; | ||
| 11 | |||
| 12 | int ways_n_1 = 1; // ways(n-1, n) | ||
| 13 | int ways_n_2 = 2; // ways(n-2, n) | ||
| 14 | for (int i = n-3; i >= 0; --i) { | ||
| 15 | const int ways_n_3 = ways_n_1 + ways_n_2; | ||
| 16 | // Update | ||
| 17 | ways_n_1 = ways_n_2; | ||
| 18 | ways_n_2 = ways_n_3; | ||
| 19 | } | ||
| 20 | return ways_n_2; | ||
| 21 | } | ||
| 22 | }; | ||
