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

climbing-stairs/kut7728.swift

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+
}

valid-anagram/kut7728.swift

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)