Subsets的解法是从空集开始,依次取每一个元素与子集中的每个集合做并操作。实现代码如下:
1 public class Subsets {
2 public ArrayList<ArrayList<Integer>> subsets(int[] S) {
3 Arrays.sort(S);
4 ArrayList<ArrayList<Integer>> subsets = new ArrayList<ArrayList<Integer>>();
5 subsets.add(new ArrayList<Integer>());
6 for (int i = 0; i < S.length; i++) {
7 int size = subsets.size();
8 for (int j = 0; j < size; j++) {
9 ArrayList<Integer> subset = new ArrayList<Integer>(
10 subsets.get(j));
11 subset.add(S[i]);
12 subsets.add(subset);
13 }
14 }
15 return subsets;
16 }
17 }
Gray Code的算法是初始时集合中只有{0, 1}两个元素,此后在每个元素的前面附加一个1。实现代码如下:
1 public class GrayCode {
2 public ArrayList<Integer> grayCode(int n) {
3 ArrayList<Integer> result = new ArrayList<Integer>();
4 if (n == 0) {
5 result.add(0);
6 return result;
7 }
8 ;
9 result.add(0);
10 result.add(1);
11 for (int i = 1; i < n; i++) {
12 ArrayList<Integer> tmp = new ArrayList<Integer>(result);
13 Integer a = 1 << i;
14 for (int k = result.size() - 1; k >= 0; k--) {
15 tmp.add(result.get(k) + a);
16 }
17 result = tmp;
18 }
19 return result;
20 }
21 }