From eda4e207a3355ff01f729bf45fdd92902abc58f0 Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 11 Feb 2024 18:27:23 +0100 Subject: [PATCH] =?UTF-8?q?swift:=20add=20=C2=AB216.=20Combination=20Sum?= =?UTF-8?q?=20III=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- swift/combination-sum-iii.swift | 40 +++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 swift/combination-sum-iii.swift diff --git a/swift/combination-sum-iii.swift b/swift/combination-sum-iii.swift new file mode 100644 index 0000000..633d11e --- /dev/null +++ b/swift/combination-sum-iii.swift @@ -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 + } +}