78.子集
回溯法
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ls = new ArrayList<>();
public List<List<Integer>> subsets(int[] nums) {
//回溯法
f(nums, 0);
return ans;
}
public void f(int[] nums, int index){
if(index == nums.length){
ans.add(new ArrayList<>(ls));
return;
}
ls.add(nums[index]);
f(nums, index+1);//选第i个
ls.remove(ls.size() - 1);
f(nums, index+1);//不选第i个
}
// List<List<Integer>> ans = new ArrayList<>();
// List<Integer> ls = new ArrayList<>();
// public List<List<Integer>> subsets(int[] nums) {
// //回溯法
// f(nums, 0);
// return ans;
// }
// public void f(int[] nums, int index){
// if(index > nums.length){//注意这里是大于号!
// return;
// }
// ans.add(new ArrayList<>(ls));
// for(int i = index;i < nums.length;i++){
// ls.add(nums[i]);
// f(nums, i+1);
// ls.remove(ls.size()-1);
// }
// }
}
90.子集Ⅱ
回溯法(带去重)
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> ls = new ArrayList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);//先排序!!
dp(nums, 0);
return ans;
}
public void dp(int[] nums, int index){
if(index > nums.length){
return;
}
ans.add(new ArrayList<Integer>(ls));
for(int i = index;i < nums.length;i++){
if(i > index && nums[i] == nums[i-1])
continue;
ls.add(nums[i]);
dp(nums, i+1);
ls.remove(ls.size()-1);
}
}
}