Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 68bfa43

Browse files
feat: add swift implementation to lcp problem: No.22 (#3772)
1 parent 3c3afac commit 68bfa43

File tree

2 files changed

+65
-0
lines changed

2 files changed

+65
-0
lines changed

‎lcp/LCP 22. 黑白方格画/README.md‎

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,41 @@ function paintingPlan(n: number, k: number): number {
195195
}
196196
```
197197

198+
#### Swift
199+
200+
```swift
201+
class Solution {
202+
func paintingPlan(_ n: Int, _ k: Int) -> Int {
203+
if k == 0 || k == n * n {
204+
return 1
205+
}
206+
207+
func combination(_ n: Int, _ r: Int) -> Int {
208+
guard r <= n else { return 0 }
209+
if r == 0 || r == n { return 1 }
210+
var result = 1
211+
for i in 0..<r {
212+
result = result * (n - i) / (i + 1)
213+
}
214+
return result
215+
}
216+
217+
var ans = 0
218+
219+
for i in 0...n {
220+
for j in 0...n {
221+
let paintedCells = n * (i + j) - i * j
222+
if paintedCells == k {
223+
ans += combination(n, i) * combination(n, j)
224+
}
225+
}
226+
}
227+
228+
return ans
229+
}
230+
}
231+
```
232+
198233
<!-- tabs:end -->
199234

200235
<!-- solution:end -->
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
class Solution {
2+
func paintingPlan(_ n: Int, _ k: Int) -> Int {
3+
if k == 0 || k == n * n {
4+
return 1
5+
}
6+
7+
func combination(_ n: Int, _ r: Int) -> Int {
8+
guard r <= n else { return 0 }
9+
if r == 0 || r == n { return 1 }
10+
var result = 1
11+
for i in 0..<r {
12+
result = result * (n - i) / (i + 1)
13+
}
14+
return result
15+
}
16+
17+
var ans = 0
18+
19+
for i in 0...n {
20+
for j in 0...n {
21+
let paintedCells = n * (i + j) - i * j
22+
if paintedCells == k {
23+
ans += combination(n, i) * combination(n, j)
24+
}
25+
}
26+
}
27+
28+
return ans
29+
}
30+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /