
思路:
回溯法
这里要注意,由于我们同一集合不同顺序的结果算同一种结果,因此我们在考虑的时候要进行排序已有元素类型的情况
代码:
class Solution {
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> res=new LinkedList<>();
getAll(0,nums,new LinkedList<Integer>(),res);
return res;
}
private void getAll(int i, int[] nums, LinkedList<Integer> curr, List<List<Integer>> res) {
res.add(new LinkedList<>(curr));
//排序第i和元素参与排序的情况,这样每次其实我们是排除了一种已有元素排序的情况
for (int j = i; j < nums.length; j++) {
if (!curr.contains(nums[j])){
curr.add(nums[j]);
getAll(j+1,nums,curr,res);
curr.removeLast();
}
}
}
}
网友评论