Subsets(lintcode 17)
Description
Given a set of distinct integers, return all possible subsets.
Notice:
Elements in a subset must be in non-descending order.
The solution set must not contain duplicate subsets.
Example
If S = [1,2,3], a solution is:
[
[3],
[1],
[2],
[1,2,3],
[1,3],
[2,3],
[1,2],
[]
]
Interface
class Solution {
/**
* @param S: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
// write your code here
}
}
Solution
class Solution {
/**
* @param S: A set of numbers.
* @return: A list of lists. All valid subsets.
*/
public ArrayList<ArrayList<Integer>> subsets(int[] nums) {
// write your code here
ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
int n = nums.length;
Arrays.sort(nums);
for (int i = 0; i < (1 << n); ++i) {
ArrayList<Integer> list = new ArrayList<Integer>();
for (int j = 0; j < n; ++j) {
if ((i & (1 << j)) != 0) {
list.add(nums[j]);
}
}
result.add(list);
}
return result;
}
}