78.子集,90集合II(数组中含有重复元素),491递增子序列
78.子集
private List<List<Integer>>res=new ArrayList<>();
private List<Integer>singleRes=new LinkedList<>();
public List<List<Integer>> subsets(int[] nums) {
res.add(new ArrayList<>());
backTrack(0,nums);
return res;
}
private void backTrack(int index,int[] nums){
if(singleRes.size()>0) {
res.add(new ArrayList<>(singleRes));
}
if(index>=nums.length){
return;
}
for(int i=index;i<nums.length;i++){
singleRes.add(nums[i]);
backTrack(i+1,nums);
singleRes.remove(singleRes.size()-1);
}
}
90.子集2
private List<List<Integer>>res=new ArrayList<>();
private List<Integer>singleRes=new LinkedList<>();
public List<List<Integer>> subsetsWithDup(int[] nums) {
res.add(new ArrayList<>());
Arrays.sort(nums);
backTrack(0,nums);
return res;
}
private void backTrack(int index,int[]nums){
if(singleRes.size()>0){
res.add(new ArrayList<>(singleRes));
}
if(index>=nums.length){
return;
}
for(int i=index;i<nums.length;i++){
if(i>index&&nums[i]==nums[i-1]){
continue;
}
singleRes.add(nums[i]);
backTrack(i+1,nums);
singleRes.remove(singleRes.size()-1);
}
}
491.递增子序列
private List<List<Integer>>res=new ArrayList<>();
private List<Integer>singleRes=new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backTrack(0,nums,Integer.MIN_VALUE);
return res;
}
private void backTrack(int index,int[]nums,int lastNum){
if(singleRes.size()>=2){
res.add(new ArrayList<>(singleRes));
}
if(index>=nums.length){
return;
}
boolean[] vis = new boolean[201];
for(int i=index;i<nums.length;i++){
if(nums[i]<lastNum){
continue;
}
if(vis[nums[i]+100]){
continue;
}
singleRes.add(nums[i]);
vis[nums[i]+100]=true;
backTrack(i+1,nums,nums[i]);
singleRes.remove(singleRes.size()-1);
}
}