swift: add «216. Combination Sum III»
Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
parent
4299b5f85a
commit
eda4e207a3
1 changed files with 40 additions and 0 deletions
40
swift/combination-sum-iii.swift
Normal file
40
swift/combination-sum-iii.swift
Normal file
|
@ -0,0 +1,40 @@
|
||||||
|
class Solution {
|
||||||
|
private struct Solver {
|
||||||
|
let k, n: Int
|
||||||
|
var combinations: [[Int]]
|
||||||
|
|
||||||
|
init(k: Int, n: Int) {
|
||||||
|
self.k = k
|
||||||
|
self.n = n
|
||||||
|
self.combinations = []
|
||||||
|
}
|
||||||
|
|
||||||
|
mutating func solve() {
|
||||||
|
var combination: [Int] = []
|
||||||
|
solve(&combination, k: k, n: n, nextDigit: 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
private mutating func solve(_ combination: inout [Int], k: Int, n: Int, nextDigit: Int) {
|
||||||
|
if k == 0 && n == 0 {
|
||||||
|
combinations.append(combination)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if k <= 0 || n <= 0 || nextDigit > 9 {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
for d in nextDigit...9 {
|
||||||
|
combination.append(d)
|
||||||
|
solve(&combination, k: k - 1, n: n - d, nextDigit: d + 1)
|
||||||
|
_ = combination.popLast()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func combinationSum3(_ k: Int, _ n: Int) -> [[Int]] {
|
||||||
|
var s = Solver(k: k, n: n)
|
||||||
|
s.solve()
|
||||||
|
return s.combinations
|
||||||
|
}
|
||||||
|
}
|
Loading…
Reference in a new issue