Subsets
2016-12-15 本文已影响23人
looper1211
Despriction
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],
[]
]
code
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>>();
if (nums == null || nums.length == 0) {
return result;
}
Arrays.sort(nums);
ArrayList<Integer> list = new ArrayList<Integer>();
subsetsHelp(result, list, nums, 0);
return result;
}
private void subsetsHelp(ArrayList<ArrayList<Integer>> result, ArrayList<Integer> list, int[] nums, int pos) {
result.add(new ArrayList<Integer>(list));
for (int i = pos; i < nums.length; i++) {
list.add(nums[i]);
subsetsHelp(result, list, nums, i + 1);
list.remove(list.size() - 1);
}
}
}