File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-0
lines changed Original file line number Diff line number Diff line change 1+ // dfs๋ฅผ ์ด์ฉํ ํ์ด
2+ // dp ๋ฐฐ์ด์ ์ด์ฉํ ๊ฒ๋ณด๋ค ๊ณต๊ฐ๋ณต์ก๋๊ฐ ์๋์ ์ผ๋ก ๋ฎ๊ฒ ์กํ 40.4mb -> 40.1mb
3+ // ์ด์ ๊ฐ ๋ญ์ง๋ ์กฐ๊ธ ๋ ๊ณ ๋ฏผํด๋ด์ผํ ๋ฏ
4+ class Solution {
5+ public int climbStairs (int n ) {
6+ return dfs (n , new HashMap <>());
7+ }
8+
9+ private int dfs (int n , Map <Integer , Integer > memo ) {
10+ if (n == 0 ) {
11+ return 1 ;
12+ }
13+ if (n < 0 ) {
14+ return 0 ;
15+ }
16+ if (memo .containsKey (n )) {
17+ return memo .get (n );
18+ }
19+
20+ int result = dfs (n - 1 , memo ) + dfs (n - 2 , memo );
21+ memo .put (n , result );
22+
23+ return result ;
24+ }
25+ }
26+
27+ // ๊ฐ์ฅ ๋จผ์ ์๊ฐํ ํ์ด
28+ // ํผ๋ณด๋์น ์์ด์ ํํ์ ๊ฒฐ๊ณผ๋ฌผ์ ๊ฐ๋๋ค.
29+ // O(N)์ ์ ํ์์ ์ธ์ธ ์ ์์ผ๋ฉด ์ด๋ ๋ฐฉ์์ผ๋ก๋ ํ๋ฆผ
30+ class Solution {
31+ public int climbStairs (int n ) {
32+ if (n == 1 ) return 1 ;
33+ if (n == 2 ) return 2 ;
34+
35+ int [] dp = new int [n + 1 ];
36+ dp [1 ] = 1 ; // 1
37+ dp [2 ] = 2 ; // 1+1, 2
38+
39+ for (int i = 3 ; i <= n ; i ++) {
40+ dp [i ] = dp [i -1 ] + dp [i -2 ];
41+ }
42+
43+ return dp [n ];
44+ }
45+ }
You canโt perform that action at this time.
0 commit comments