78题目有很多种解法,但是此处按照博客目的,先只列出二进制位运算的答案。
特别需要注意的是,引用类型的浅拷贝*
对于引用类型的拷贝问题,由于语言差异,此处使用的是重新申明而不是深拷贝的额方法。
Python 3 代码
class Solution(object):
def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = [[]]
for num in nums :
for temp in res[:] :
x = temp[:]
x.append(num)
res.append(x)
return res
C# 代码
public class Solution
{
public IList<IList<int>> Subsets(int[] nums)
{
int maxLen =1<< nums.Length;
IList<IList<int>> result = new List<IList<int>>();
for(int ele=0;ele<maxLen;ele++)
{
char[] idx = Convert.ToString(ele,2).PadLeft(nums.Length,'0').ToCharArray();
IList<int> subset = new List<int>();
for(int i=0;i<idx.Length;i++)
{
if(idx[i]=='1')
{
subset.Add(nums[i]);
}
}
result.Add(subset);
}
return result;
}
}