# leetcode 78.Subsets

#每天挖坑，填坑

000 对应[]
001 对应[3]
010 对应[2]
011 对应[2,3]

java

public List<List<Integer>> subsets(int[] nums) {
int n = nums.length;
List<List<Integer>> subsets = new ArrayList<>();
for (int i =0; i <Math.pow(2,n);i++)
{
List<Integer> subset = new ArrayList<>();
for (int j =0; j <n;j++)
{
if(((1<<j)& i )!= 0)
}
Collections.sort(subset);
}
return subsets;
}
}

python

def subsets(self, nums):
res = []
nums.sort()
for i in xrange(1<<len(nums)):
tmp = []
for j in xrange(len(nums)):
if i & 1 << j:  # if i >> j & 1:
tmp.append(nums[j])
res.append(tmp)
return res

1. 最外层循环逐一从 nums 数组中取出每个元素 num
2. 内层循环从原来的结果集中取出每个中间结果集，并向每个中间结果集中添加该 num 元素
3. 往每个中间结果集中加入 num
4. 将新的中间结果集加入结果集中
python
def subsets(self, nums):
res = [[]]
for num in sorted(nums):
res += [item+[num] for item in res]
return res

java

public List<List<Integer>> subsets(int[] nums) {

List<List<Integer>> res = new ArrayList<List<Integer>>();

for(int num:nums){
int size = res.size();
for(int i = 0;i <size ; i++){
List<Integer> temp  = new ArrayList(res.get(i));
}
}
return res;
}
}

java

public List<List<Integer>> subsets(int[] S) {
List<List<Integer>> result = new ArrayList<>();
Arrays.sort(S);
getSubsets(result, new ArrayList<Integer>(), S, 0);
return result;
}
private void getSubsets(List<List<Integer>> result, List<Integer> list, int[] S, int start) {
for(int i=start; i<S.length; i++) {
getSubsets(result, list, S, i+1);
list.remove(list.size()-1);
}
}

python

def subsets(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
self.dfs(sorted(nums), 0, [], res)
return res

def dfs(self, nums, index, path, res):
res.append(path)
for i in range(index, len(nums)):
self.dfs(nums, i+1, path+[nums[i]], res)

• 广告
• 抄袭
• 版权
• 政治
• 色情
• 无意义
• 其他

120