题目:子集
- 题号:78
- 难度:中等
- https://leetcode-cn.com/problems/subsets/
给你一个整数数组 nums ,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例1:
输入: nums = [1,2,3]
输出:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
示例2:
输入:nums = [0]
输出:
[
[],
[0]
]
实现
第一种:回溯法
依次以nums[i]为启始点进行搜索,且后续搜索数值都要大于前一个数值,这样会避免重复搜索。
C# 语言
public class Solution
{
private IList<IList<int>> _result;
public IList<IList<int>> Subsets(int[] nums)
{
_result = new List<IList<int>>();
int len = nums.Length;
if (len == 0)
{
return _result;
}
IList<int> item = new List<int>();
Find(nums, 0, item);
return _result;
}
private void Find(int[] nums, int begin, IList<int> item)
{
// 注意:这里要 new 一下
_result.Add(new List<int>(item));
if (begin == nums.Length)
return;
for (int i = begin; i < nums.Length; i++)
{
item.Add(nums[i]);
Find(nums, i + 1, item);
// 组合问题,状态在递归完成后要重置
item.RemoveAt(item.Count - 1);
}
}
}
第二种:子集扩展法
C# 语言
public class Solution
{
public IList<IList<int>> Subsets(int[] nums)
{
IList<IList<int>> result = new List<IList<int>>();
IList<int> item = new List<int>();
result.Add(item);
for (int i = 0; i < nums.Length; i++)
{
for (int j = 0, len = result.Count; j < len; j++)
{
item = new List<int>(result[j]);
item.Add(nums[i]);
result.Add(item);
}
}
return result;
}
}
第三种:位运算
思路: 利用整数集合的思路。
以{1,2,3}
为例,三个数,共2^3
个子集。
000 -> []
100 -> [1]
101 -> [1,3]
110 -> [1,2]
111 -> [1,2,3]
...
C# 语言
public class Solution
{
public IList<IList<int>> Subsets(int[] nums)
{
IList<IList<int>> result = new List<IList<int>>();
int count = nums.Length;
for (int i = 0; i < 1 << count; i++)
{
IList<int> item = new List<int>();
for (int j = 0; j < count; j++)
{
int mask = 1 << j;
if ((mask & i) != 0)
item.Add(nums[j]);
}
result.Add(item);
}
return result;
}
}
Python 语言
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
count = len(nums)
result = []
for i in range(1 << count):
item = []
for j in range(count):
mask = 1 << j
if (mask & i) != 0:
item.append(nums[j])
result.append(item)
return result