Skip to content

Commit b3d1aea

Browse files
authored
feat: add swift solution 2 implementation to lcp problem: No.07 (#3743)
1 parent 83f3c4e commit b3d1aea

File tree

2 files changed

+43
-0
lines changed

2 files changed

+43
-0
lines changed

lcp/LCP 07. 传递信息/README.md

+24
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,30 @@ function numWays(n: number, relation: number[][], k: number): number {
255255
}
256256
```
257257

258+
#### Swift
259+
260+
```swift
261+
class Solution {
262+
func numWays(_ n: Int, _ relation: [[Int]], _ k: Int) -> Int {
263+
var f = Array(repeating: 0, count: n)
264+
f[0] = 1
265+
var steps = k
266+
267+
while steps > 0 {
268+
var g = Array(repeating: 0, count: n)
269+
for r in relation {
270+
let a = r[0], b = r[1]
271+
g[b] += f[a]
272+
}
273+
f = g
274+
steps -= 1
275+
}
276+
277+
return f[n - 1]
278+
}
279+
}
280+
```
281+
258282
<!-- tabs:end -->
259283

260284
<!-- solution:end -->
+19
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
class Solution {
2+
func numWays(_ n: Int, _ relation: [[Int]], _ k: Int) -> Int {
3+
var f = Array(repeating: 0, count: n)
4+
f[0] = 1
5+
var steps = k
6+
7+
while steps > 0 {
8+
var g = Array(repeating: 0, count: n)
9+
for r in relation {
10+
let a = r[0], b = r[1]
11+
g[b] += f[a]
12+
}
13+
f = g
14+
steps -= 1
15+
}
16+
17+
return f[n - 1]
18+
}
19+
}

0 commit comments

Comments
 (0)