Given a set of distinct integers, nums, 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 nums = [1,2,3]
, a solution is:
[ [3], [1], [2], [1,2,3], [1,3], [2,3], [1,2], [] ]
Subscribe to see which companies asked this question
题解:使用递归
code:
public class Solution {
public List<List<Integer>> subsets(int[] nums) {
Arrays.sort(nums);
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> res = new ArrayList<Integer>();
sovle(0, nums.length, nums, res, ans);
return ans;
}
private void sovle(int cur ,int length, int[] nums, List<Integer> res, List<List<Integer>> ans)
{
ans.add(new ArrayList<Integer>(res));
for(int i = cur; i<length; i++)
{
res.add(nums[i]);
sovle(i+1 ,length, nums, res, ans);
res.remove(res.size() - 1);
}
}
}