Skip to content

Commit 01afec6

Browse files
committed
valid-anagram solved
1 parent ade5a51 commit 01afec6

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
class Solution {
2+
//๊ณ„๋‹จ ๊ฐฏ์ˆ˜ n ์ž…๋ ฅ๋ฐ›์Œ
3+
func climbStairs(_ n: Int) -> Int {
4+
var result = 0
5+
6+
///1๊ณ„๋‹จ์”ฉ ์˜ฌ๋ผ๊ฐ€๋Š” ๊ฒฝ์šฐ = 1์Šคํƒญ
7+
///2๊ณ„๋‹จ์”ฉ ์˜ฌ๋ผ๊ฐ€๋Š” ๊ฒฝ์šฐ = 2์Šคํƒญ
8+
///2์Šคํƒญ์ธ ๊ฒฝ์šฐ๋ฅผ 1์”ฉ ์ฆ๊ฐ€์‹œ์ผœ์คŒ
9+
for i in 0...(n/2) {
10+
///2์Šคํƒญ์ด ์—†๋Š” ๊ฒฝ์šฐ -> ์ „๋ถ€ 1์Šคํƒญ์ž„
11+
if i == 0 {
12+
result += 1
13+
continue
14+
}
15+
16+
///n์—์„œ 2์Šคํƒญ ํšŸ์ˆ˜๋ฅผ ๋นผ์„œ 1์Šคํƒญ ํšŸ์ˆ˜ ๊ตฌํ•˜๊ธฐ
17+
let x = n - (2 * i)
18+
19+
///์กฐํ•ฉ๊ณ„์‚ฐ์‹ (2์Šคํƒญ,1์Šคํƒญ ์ „์ฒด ํšŸ์ˆ˜ C 2์Šคํƒญ ํšŸ์ˆ˜)
20+
result += ncm(x+i, i)
21+
}
22+
23+
return result
24+
}
25+
26+
///ncmํ•จ์ˆ˜๋กœ ์กฐํ•ฉ ๊ณ„์‚ฐ์‹์„ ๊ตฌํ˜„
27+
func ncm(_ n: Int, _ m: Int) -> Int {
28+
if m == 1 { return n } ///nC1 ์ด๋ผ๋ฉด ์ „์ฒดํšŸ์ˆ˜ n ๋ฐ˜ํ™˜
29+
if m == n { return 1 } ///nCn ์ด๋ผ๋ฉด 1๋ฐ˜ํ™˜
30+
31+
///์กฐํ•ฉ ๊ณ„์‚ฐ์‹์„ ์ฝ”๋“œ๋กœ ๊ณ„์‚ฐํ•  ์ˆ˜ ์žˆ๋„๋ก ์ตœ์ ํ™”ํ•˜๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™์•„์ง
32+
return (1...m).reduce(1) { $0 * ($1 + n-m)/$1 }
33+
}
34+
}
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
class Solution {
2+
func climbStairs(_ n: Int) -> Int {
3+
var result = 0
4+
5+
for i in 0...(n/2) {
6+
if i == 0 {
7+
result += 1
8+
continue
9+
}
10+
11+
let x = n - (2 * i)
12+
13+
result += ncm(x+i, i)
14+
}
15+
16+
return result
17+
}
18+
19+
func ncm(_ n: Int, _ m: Int) -> Int {
20+
if m == 1 { return n }
21+
if m == n { return 1 }
22+
return (1...m).reduce(1) { $0 * ($1 + n-m)/$1 }
23+
}
24+
}

0 commit comments

Comments
ย (0)