回溯法
一般情况下,看到题目要求「所有可能的结果」,而不是「结果的个数」,我们就知道需要暴力搜索所有的可行解了,可以用「回溯法」。
「回溯法」实际上一个类似枚举的搜索尝试过程,主要是在搜索尝试过程中寻找问题的解,当发现已不满足求解条件时,就「回溯」返回,尝试别的路径。
回溯法是一种算法思想,而递归是一种编程方法,回溯法可以用递归来实现。
回溯法的整体思路是:搜索每一条路,每次回溯是对具体的一条路径而言的。对当前搜索路径下的的未探索区域进行搜索,则可能有两种情况:
当前未搜索区域满足结束条件,则保存当前路径并退出当前搜索;
当前未搜索区域需要继续搜索,则遍历当前所有可能的选择:如果该选择符合要求,则把当前选择加入当前的搜索路径中,并继续搜索新的未探索区域。
上面说的未搜索区域是指搜索某条路径时的未搜索区域,并不是全局的未搜索区域。
回溯法搜所有可行解的模板一般是这样的:
class Solution {
List<List<Integer>> res;
List<Integer> path;
public List<List<Integer>> subsets(int[] nums) {
res = new ArrayList<>();
path = new ArrayList<>();
helper(nums,res,path,0);
return res;
}
public void helper(int[] nums,List<List<Integer>> res,List<Integer> path,int start){
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++){
path.add(nums[i]);
helper(nums,res,path,i+1);
path.remove(path.size()-1);
}
}
}
难度中等
给你一个整数数组 nums
,数组中的元素 互不相同 。返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。你可以按 任意顺序 返回解集。
示例 1:
输入:nums = [1,2,3]
输出:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
可以直接使用模板解题:
class Solution {
List<List<Integer>> res;
List<Integer> path;
public List<List<Integer>> subsets(int[] nums) {
res = new ArrayList<>();
path = new ArrayList<>();
helper(nums,res,path,0);
return res;
}
public void helper(int[] nums,List<List<Integer>> res,List<Integer> path,int start){
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++){
path.add(nums[i]);
helper(nums,res,path,i+1);
path.remove(path.size()-1);
}
}
}
难度中等
给你一个整数数组 nums
,其中可能包含重复元素,请你返回该数组所有可能的子集(幂集)。
解集 不能 包含重复的子集。返回的解集中,子集可以按 任意顺序 排列。
示例 1:
输入:nums = [1,2,2]
输出:[[],[1],[1,2],[1,2,2],[2],[2,2]]
示例 2:
输入:nums = [0]
输出:[[],[0]]
这道题相比上一道题多了去重的步骤,所以在看懂上一道题的情况下,这道题就是如何理解去重了。如果你能理解上面的回溯法,那么包含重复元素的数组的子集,只不过一个小的改进。
重复子列出现在哪些部分? 假设元素列(nums)为:[1, 2, 2],下面进行模拟
- 遍历完第一个元素--->[[], [1]]
- 遍历完第二个元素--->[[], [1], [2], [1, 2]]
- 遍历完第三个元素--->[[], [1], [2], [1, 2], **[2]**, **[1, 2]**, [2, 2], [1, 2, 2]]。
- **[2]**, **[1, 2]**为重复元素
比如说求 nums = [1,2,2] 的子集,那么对于子集 [1,2] 是选择了第一个 2,那么就不能再选第二个 2 来构成 [1,2] 了。所以,此时的改动点,就是先排序,每个元素 nums[i] 添加到 path 之前,判断一下 nums[i] 是否等于 nums[i - 1] ,如果相等就不添加到 path 中。
class Solution {
List<List<Integer>> res;
List<Integer> path;
public List<List<Integer>> subsetsWithDup(int[] nums) {
Arrays.sort(nums);
res = new ArrayList<>();
path = new ArrayList<>();
helper(nums,res,path,0);
return res;
}
public void helper(int[] nums,List<List<Integer>> res,List<Integer> path ,int start){
res.add(new ArrayList<>(path));
for(int i=start;i<nums.length;i++){
if(i != start && nums[i] == nums[i-1]){
continue;
}
path.add(nums[i]);
helper(nums,res,path,i+1);
path.remove(path.size()-1);
}
}
}