Scribbling

LeetCode: 90. Subsets II 본문

Computer Science/Coding Test

LeetCode: 90. Subsets II

focalpoint 2021. 10. 10. 23:50
class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        self.ret = []
        self.dfs(nums, [])
        return self.ret
        
    def dfs(self, nums, path):
        self.ret.append(path)
        prev = None
        for i, num in enumerate(nums):
            if num != prev:
                prev = num
                self.dfs(nums[i+1:], path+[num])

 

Lazy version:

class Solution:
    def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
        nums.sort()
        self.ret = []
        for p in self.gen(nums, []):
            self.ret.append(p)
        return self.ret
        
    def gen(self, nums, path):
        yield path
        prev = None
        for i, num in enumerate(nums):
            if num != prev:
                prev = num
                yield from self.gen(nums[i+1:], path+[num])

'Computer Science > Coding Test' 카테고리의 다른 글

LeetCode: 91. Decode Ways  (0) 2021.10.11
LeetCode: 100. Same Tree  (0) 2021.10.11
LeetCode: 88. Merge Sorted Array  (0) 2021.10.09
LeetCode: 98. Validate Binary Search Tree  (0) 2021.10.09
LeetCode: 99. Recover Binary Search Tree  (0) 2021.10.08