Given a set of distinct integers, S, return all possible subsets.
Note:
- Elements in a subset must be in non-descending order.
- The solution set must not contain duplicate subsets.
For example,
If S = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
package leetcode;
import java.util.ArrayList;
import java.util.Arrays;
public class Subsets {
public ArrayList<ArrayList<Integer>> subsets(int[] S) {
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> r = new ArrayList<Integer>();
result.add(r);
if (S == null || S.length == 0) {
return result;
}
Arrays.sort(S);
int[] pos = new int[S.length + 1];
for (int len = 1; len <= S.length; len++) {
Arrays.fill(pos, -1);
int index = 1;
while (index >= 1) {
if (pos[index] == -1) {
pos[index] = pos[index - 1] + 1;
} else {
pos[index]++;
}
if (pos[index] < S.length) {
if (index == len) {
ArrayList<Integer> rr = new ArrayList<Integer>();
for (int i = 1; i <= len; i++) {
rr.add(S[pos[i]]);
}
result.add(rr);
} else {
pos[index + 1] = -1;
index++;
}
} else {
index--;
}
}
}
return result;
}
}