leetcode 每日一题 90. 子集 II
回溯法
思路:
参考78.子集,在添加子集的时候多了判断去重操作。
代码:
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: def backtrack(path = [],begin = 0): if len(path) == k: res.append(path[:]) return for i in range(begin,len(nums)): if i !=begin and nums[i]==nums[i-1]: continue path.append(nums[i]) backtrack(path,i+1) path.pop() nums.sort() res = [] for k in range(len(nums)+1): backtrack() return res
递归
思路:
参考78.子集,在添加子集的时候多了判断去重操作。
代码:
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums.sort() output = [[]] for num in nums: temp = output[:] for curr in temp: sub = curr + [num] if sub not in output: output += [sub] return output
二进制排序
思路:
参考78.子集,在添加子集的时候多了判断去重操作。
代码:
class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: nums.sort() n = len(nums) output = [] for i in range(2**n, 2**(n + 1)): bitmask = bin(i)[3:] temp = [] for j in range(n): if bitmask[j] == '1': temp.append(nums[j]) if temp not in output: output.append(temp) return output