题目链接:https://leetcode.com/problems/subsets/
思路:回溯递归。
AC 1ms 100% Java:
class Solution {
private List<List<Integer>> ans=new ArrayList();
public List<List<Integer>> subsets(int[] nums) {
Arrays.sort(nums);
helper(nums,0,new ArrayList<Integer>());
return ans;
}
public void helper(int[]nums,int start,List<Integer> list){
ans.add(new ArrayList(list));
for(int i=start;i<nums.length;i++){
list.add(nums[i]);
helper(nums,i+1,list);
list.remove(list.size()-1);
}
}
}
这样递归保证了一种顺序,
空 ,1 , 1 2 ,1 2 3 , 2 , 2 3 , 3;