Swift solution - Backtracking


  • 0
    class Solution {
        func combinationSum3(_ k: Int, _ n: Int) -> [[Int]] {
            var result = [[Int]]()
            var candidate = [Int]()
            
            backtracking(k, n, 1, &candidate, &result)
            
            return result
        }
        
        private func backtracking(_ k: Int, _ n: Int, _ start: Int, _ candidate: inout [Int], _ result: inout [[Int]]) {
            if candidate.count == k && n == 0 {
                result.append(candidate)
                return
            }
            
            for i in stride(from: start, through: 9, by: 1) {
                candidate.append(i)
                backtracking(k, n - i, i + 1, &candidate, &result)
                candidate.removeLast()
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.