Swift solution - Backtracking


  • 0
    class Solution {
        func subsetsWithDup(_ nums: [Int]) -> [[Int]] {
            var result = [[Int]]()
            var candidate = [Int]()
            
            backtracking(&result, &candidate, nums.sorted(), 0)
            
            return result
        }
        
        private func backtracking(_ result: inout [[Int]], _ candidate: inout [Int], _ nums: [Int], _ start: Int) {
            result.append(candidate)
            for i in start..<nums.count {
                if i == start || nums[i] != nums[i - 1] {
                    candidate.append(nums[i])
                    backtracking(&result, &candidate, nums, i + 1)
                    candidate.removeLast()
                }
            }
        }
    }
    

Log in to reply
 

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