Given a set of distinct integers, S, return all possible subsets.
Note:
For example,
If S = [1,2,3]
, a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
解题思路:
这道题目拿到手第一想法就是利用DFS,与以往不同的是子集的大小是从0到3,这个点需要额外注意,本初就是在主函数中构造一个for循环来解决这个问题,剩下的就是整张的dfs算法。当然我在此处天添加了visited 和 start,就我个人的经验来说,我认为i这种集合顺序性存在的题目,怎么说呢 就是 12345567 用第一个再用第二个再用第三个的 用start明显好一些。
class Solution {
public List> subsets(int[] nums) {
List> subset = new ArrayList<>();
List subsetList = new ArrayList<>();
boolean[] visited = new boolean[nums.length];
for(int i=0; i <= nums.length; i++)
help(subset, subsetList, visited, 0, i, nums);
return subset;
}
private void help(List> subset, List subsetList,
boolean[] visited, int start, final int size, final int[] nums){
if(subsetList.size() == size){
subset.add(new ArrayList<>(subsetList));
return;
}
for(int i = start; i < nums.length; i++){
subsetList.add(nums[i]);
help(subset, subsetList, visited, i + 1, size, nums);
subsetList.remove(subsetList.size() - 1);
}
}
}
class Solution {
public List> subsets(int[] nums) {
List> result = new ArrayList<>();
List list = new ArrayList<>();
result.add(new ArrayList());
boolean[] visited = new boolean[nums.length];
help(list, result, nums, 0, visited);
return result;
}
private void help(List list, List> result, int[] nums, int start,
boolean[] visited){
for(int i = start; i < nums.length; i++){
visited[i] = true;
list.add(nums[i]);
if(list.size() <= nums.length)
result.add(new ArrayList(list));
help(list, result, nums, i+1, visited);
list.remove(list.size() - 1);
}
}
}