Subsets

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],
  []
]
这题和Combinations一样。 也可以用位运算做。
 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> subsets(int[] S) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 6         for(int i = 0; i < Math.pow(2, S.length); i ++){
 7             ArrayList<Integer> row = new ArrayList<Integer>();
 8             for(int j = 0; j < S.length; j ++){
 9                 if((i >> j & 1) == 1) row.add(S[j]);
10             }
11             result.add(row);
12         }
13         return result;
14     }
15 }

这个做法 的顺序不对。 改进后如下:

 1 public class Solution {
 2     public ArrayList<ArrayList<Integer>> subsets(int[] S) {
 3         // Start typing your Java solution below
 4         // DO NOT write main() function
 5         Arrays.sort(S);
 6         ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
 7         for(int i = 0; i < (1 << S.length); i ++){
 8             ArrayList<Integer> row = new ArrayList<Integer>();
 9             for(int j = 0; j < S.length; j ++){
10                 if((i & (1 << j)) != 0) row.add(S[j]);
11             }
12             result.add(row);
13         }
14         return result;
15     }
16 }
原文地址:https://www.cnblogs.com/reynold-lei/p/3420607.html