LeetCode | 0090. Subsets II子集II【Python】

逃离我推掉我的手 2022-12-24 11:00 218阅读 0赞

Problem

LeetCode

Given a collection of integers that might contain duplicates, nums, return all possible subsets (the power set).

Note: The solution set must not contain duplicate subsets.

Example:

  1. Input: [1,2,2]
  2. Output:
  3. [
  4. [2],
  5. [1],
  6. [1,2,2],
  7. [2,2],
  8. [1,2],
  9. []
  10. ]

问题

力扣

给定一个可能包含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。

说明: 解集不能包含重复的子集。

示例:

  1. 输入: [1,2,2]
  2. 输出:
  3. [
  4. [2],
  5. [1],
  6. [1,2,2],
  7. [2,2],
  8. [1,2],
  9. []
  10. ]

思路

回溯

  1. LeetCode 0070 题基础上,判断当前元素是否和前一个元素相同,相同就剪枝。
Python3 代码
  1. from typing import List
  2. class Solution:
  3. def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
  4. res = []
  5. n = len(nums)
  6. # 先对 nums 进行排序
  7. nums.sort()
  8. def backtrack(nums, start, path):
  9. # 加入 res
  10. res.append(path)
  11. # i 从 start 开始递增
  12. for i in range(start, n):
  13. # 剪枝:当前元素和前一个元素相同
  14. if i > start and nums[i - 1] == nums[i]:
  15. continue
  16. # 回溯及更新 path
  17. # path.append([nums[i]])
  18. backtrack(nums, i + 1, path + [nums[i]])
  19. # path.pop()
  20. backtrack(nums, 0, [])
  21. return res

GitHub 链接

Python

发表评论

表情:
评论列表 (有 0 条评论,218人围观)

还没有评论,来说两句吧...

相关阅读