File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ /*
2+ You are climbing a staircase. It takes n steps to reach the top.
3+
4+ Each time you can either climb 1 or 2 steps.
5+ In how many distinct ways can you climb to the top?
6+
7+ Example 1:
8+
9+ Input: n = 2
10+ Output: 2
11+ Explanation: There are two ways to climb to the top.
12+ 1. 1 step + 1 step
13+ 2. 2 steps
14+
15+ Constraints:
16+ 1 <= n <= 45
17+ */
18+
19+ // TimeComplexity : O(n)
20+ // SpaceComplexity : O(n)
21+ #include < iostream>
22+ using namespace std ;
23+
24+ #pragma region DpArrayIdea
25+ namespace dp_array_idea {
26+
27+ class Solution {
28+ public:
29+ int climbStairs (int n) {
30+ int dp[45 ];
31+
32+ // dp[i]는 i-1번째 칸을 오르는 경우의 수를 말한다.
33+ dp[0 ] = 1 ;
34+ dp[1 ] = 2 ;
35+
36+ for (int i = 2 ; i < n; i++) {
37+ dp[i] = dp[i-1 ] + dp[i-2 ];
38+ }
39+
40+ return dp[n-1 ];
41+ }
42+ };
43+
44+ } // namespace dp_array_idea
45+ #pragma endregion
46+
47+ // 배열을 사용하지 않는 풀이
48+ // Time : O(n)
49+ // Space : O(1)
50+ #pragma region FinalSolution
51+ class Solution {
52+ public:
53+ int climbStairs (int n) {
54+ if (n <= 2 ) {
55+ return n;
56+ }
57+
58+ int one_back = 1 ;
59+ int two_back = 2 ;
60+
61+ for (int i = 3 ; i <= n; i++) {
62+ int current = one_back + two_back;
63+ two_back = one_back;
64+ one_back = current;
65+ }
66+
67+ return one_back;
68+ }
69+ };
70+ #pragma endregion
You can’t perform that action at this time.
0 commit comments