Title description
Now there is a set S of integers without repeating elements. Find all subsets of S.
Note:
The elements in the subset you give must be arranged in a non-increasing order.
No duplicate elements can appear in the solution set.
For example:
if S = [ 1,2,3], the solution set should be:
[↵ [3], ↵ [1], ↵ [2], ↵ [1,2,3], ↵ [1,3], ↵ [2 , 3], ↵ [1,2], ↵ [] ↵]
analysis
- Each element must choose to join the opportunity not to join the set.
- So you can use the backtracking method, each position can be empty, can be an element of the position.
java code
import java.util.*;
public class Solution {
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
if(S == null || S.length == 0){
return res;
}
Arrays.sort(S);
helperSub(S,0,new ArrayList<>(),res);
Collections.sort(res, new Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
if (o1.size()!=o2.size()) {
return o1.size()-o2.size();
}else {
for (int i = 0; i < o1.size(); i++) {
int comp=o1.get(i)-o2.get(i);
if (comp!=0) return comp;
}
}
return 0;
}
});
return res;
}
private void helperSub(int[] s, int curIndex, ArrayList<Integer> cur, ArrayList<ArrayList<Integer>> res) {
if(curIndex == s.length){
res.add(new ArrayList<>(cur));
}else{
//CurIndex处的 s元素不加入集合内
helperSub(s,curIndex+1,cur,res);
//curIndex 处 s元素加入集合内
cur.add(s[curIndex]);
helperSub(s,curIndex+1,cur,res);
cur.remove(cur.size()-1);
}
}
}
Method two
import java.util.*;
public class Solution {
ArrayList<ArrayList<Integer>> listAll = new ArrayList<>();
public ArrayList<ArrayList<Integer>> subsets(int[] num) {
if (num == null || num.length <= 0)
return listAll;
ArrayList<Integer> list = new ArrayList<>();
Arrays.sort(num);
Findsubset(num, 0, list);
//排序
Collections.sort(listAll, new Comparator<ArrayList<Integer>>() {
@Override
public int compare(ArrayList<Integer> o1, ArrayList<Integer> o2) {
if (o1.size()!=o2.size()) {
return o1.size()-o2.size();
}else {
for (int i = 0; i < o1.size(); i++) {
int comp=o1.get(i)-o2.get(i);
if (comp!=0) return comp;
}
}
return 0;
}
});
return listAll;
}
public void Findsubset(int[] set, int start, ArrayList<Integer> list) {
listAll.add(new ArrayList<>(list));
for (int i = start; i < set.length; i++) {
list.add(set[i]);
Findsubset(set, i + 1, list);
list.remove(list.size() - 1);
}
}
}