题目描述
思路:
若数组中有n个元素,则所有子集的个数为pow(2,n)。
我们可以用二进制来解决这个问题。
举个例子:若 int [ ]nums={1,2,3},则有以下情况:
- [ 0 0 0 ]对应[ ]
- [ 0 0 1 ]对应[3]
- [ 0 1 0 ]对应[2]
- [ 1 0 0 ]对应[1]
- [ 0 1 1 ]对应[2 3]
- [ 1 0 1 ]对应[1 3]
- [ 1 1 0 ]对应[1 2]
- [ 1 1 1 ]对应[1 2 3]
这个方法其实就是将二进制与子集之间一一对应起来,每完成一个子集就将该子集插入list中,最后返回list即可。
代码如下:
public class Solution {
public IList<IList<int>> Subsets(int[] nums)
{
IList<IList<int>> list = new List<IList<int>>();
int len = nums.Length;
for (int i = 0; i < Math.Pow(2,len); i++)
{
IList<int> list1 = new List<int>();
string temp = string.Empty;
temp = Convert.ToString(i, 2).PadLeft(len, '0');
for (int j = 0; j < len; j++)
{
if (temp[j] == '1')
{
list1.Add(nums[j]);
}
}
list.Add(list1);
}
return list;
}
}