Skip to content

feat: add swift implementation to lcci problem: No.08.01 #2683

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Apr 29, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions lcci/08.01.Three Steps Problem/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,26 @@ int waysToStep(int n) {
}
```

```swift
class Solution {
func waysToStep(_ n: Int) -> Int {
let mod = Int(1e9) + 7
var a = 1, b = 2, c = 4
if n == 1 { return a }
if n == 2 { return b }
if n == 3 { return c }

for _ in 1..<n {
let t = a
a = b
b = c
c = ((a + b) % mod + t) % mod
}
return a
}
}
```

<!-- tabs:end -->

### 方法二:矩阵快速幂加速递推
Expand Down
20 changes: 20 additions & 0 deletions lcci/08.01.Three Steps Problem/README_EN.md
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,26 @@ int waysToStep(int n) {
}
```

```swift
class Solution {
func waysToStep(_ n: Int) -> Int {
let mod = Int(1e9) + 7
var a = 1, b = 2, c = 4
if n == 1 { return a }
if n == 2 { return b }
if n == 3 { return c }

for _ in 1..<n {
let t = a
a = b
b = c
c = ((a + b) % mod + t) % mod
}
return a
}
}
```

<!-- tabs:end -->

### Solution 2: Matrix Quick Power to Accelerate Recursion
Expand Down
17 changes: 17 additions & 0 deletions lcci/08.01.Three Steps Problem/Solution.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
class Solution {
func waysToStep(_ n: Int) -> Int {
let mod = Int(1e9) + 7
var a = 1, b = 2, c = 4
if n == 1 { return a }
if n == 2 { return b }
if n == 3 { return c }

for _ in 1..<n {
let t = a
a = b
b = c
c = ((a + b) % mod + t) % mod
}
return a
}
}