Skip to content

Commit 7a355b5

Browse files
authored
feat: add swift implementation to lcci problem: No.08.06 (doocs#2688)
1 parent e2467c2 commit 7a355b5

File tree

3 files changed

+51
-0
lines changed

3 files changed

+51
-0
lines changed

lcci/08.06.Hanota/README.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,24 @@ function hanota(A: number[], B: number[], C: number[]): void {
126126
}
127127
```
128128

129+
```swift
130+
class Solution {
131+
func hanota(_ A: inout [Int], _ B: inout [Int], _ C: inout [Int]) {
132+
dfs(n: A.count, a: &A, b: &B, c: &C)
133+
}
134+
135+
private func dfs(n: Int, a: inout [Int], b: inout [Int], c: inout [Int]) {
136+
if n == 1 {
137+
c.append(a.removeLast())
138+
return
139+
}
140+
dfs(n: n - 1, a: &a, b: &c, c: &b)
141+
c.append(a.removeLast())
142+
dfs(n: n - 1, a: &b, b: &a, c: &c)
143+
}
144+
}
145+
```
146+
129147
<!-- tabs:end -->
130148

131149
### 方法二:迭代(栈)

lcci/08.06.Hanota/README_EN.md

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,24 @@ function hanota(A: number[], B: number[], C: number[]): void {
131131
}
132132
```
133133

134+
```swift
135+
class Solution {
136+
func hanota(_ A: inout [Int], _ B: inout [Int], _ C: inout [Int]) {
137+
dfs(n: A.count, a: &A, b: &B, c: &C)
138+
}
139+
140+
private func dfs(n: Int, a: inout [Int], b: inout [Int], c: inout [Int]) {
141+
if n == 1 {
142+
c.append(a.removeLast())
143+
return
144+
}
145+
dfs(n: n - 1, a: &a, b: &c, c: &b)
146+
c.append(a.removeLast())
147+
dfs(n: n - 1, a: &b, b: &a, c: &c)
148+
}
149+
}
150+
```
151+
134152
<!-- tabs:end -->
135153

136154
### Solution 2: Iteration (Stack)

lcci/08.06.Hanota/Solution.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
class Solution {
2+
func hanota(_ A: inout [Int], _ B: inout [Int], _ C: inout [Int]) {
3+
dfs(n: A.count, a: &A, b: &B, c: &C)
4+
}
5+
6+
private func dfs(n: Int, a: inout [Int], b: inout [Int], c: inout [Int]) {
7+
if n == 1 {
8+
c.append(a.removeLast())
9+
return
10+
}
11+
dfs(n: n - 1, a: &a, b: &c, c: &b)
12+
c.append(a.removeLast())
13+
dfs(n: n - 1, a: &b, b: &a, c: &c)
14+
}
15+
}

0 commit comments

Comments
 (0)