Swift, DFS, using map to erase duplicates


  • 0
    X

    Is there a better way to do this without using map? I solve it yet the runtime is not so fast.

    class Solution {
    
        var resultMap = [String:[Int]]() // save items as "122" for key, [1,2,2] as value; 
        
        func subsetsWithDup(_ nums: [Int]) -> [[Int]] {
            var tmp = [Int]()
            dfs(nums: nums, idx: 0, tmp: tmp)
            
            var result = [[Int]]()
            for rlt in resultMap {
                result.append(rlt.value)
            }
            return result
        }
        
        func dfs(nums: [Int], idx: Int, tmp: [Int]) {
            var getTmp = tmp
            getTmp.sort(){$0 < $1}
            
            var key = ""
            for digit in getTmp { // make int as str key;
                key += "\(digit)"
            }
            // then put into result, already removes duplicates:
            resultMap[key] = getTmp
            
            for i in idx..<nums.count {
                getTmp.append(nums[i])
                dfs(nums:nums, idx: i+1, tmp: getTmp)
                getTmp.removeLast()
            }
        }
        
    }
    

Log in to reply
 

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