Swift solution - Backtracking


  • 0
    class Solution {
        func findSubsequences(_ nums: [Int]) -> [[Int]] {
            if nums.count == 0 {
                return []
            }
            
            var result = [[Int]]()
            var candidate = [Int]()
            
            backtracking(nums, 0, &candidate, &result)
            
            return result
        }
        
        private func backtracking(_ nums: [Int], _ pos: Int, _ candidate: inout [Int], _ result: inout [[Int]]) {
            if candidate.count >= 2 {
                result.append(candidate)
            }
            
            var visited = Set<Int>()
            
            for i in pos..<nums.count {
                if visited.contains(nums[i]) {
                    continue
                }
                if candidate.count == 0 || candidate.last! <= nums[i] {
                    visited.insert(nums[i])
                    candidate.append(nums[i])
                    backtracking(nums, 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.