Problem 1 Subset I (combination)母题
Method 1: 加或者不加(只对combination问题有效) ==》 要么要么
High Level:题目让我们求出all subsets
step1:什么是一个解?一个subset是一个解
step2:如何构造一个解?
每一层是什么?考虑一个元素
分支是什么?要么加,要么不加
在哪里收集解?一共有多少层?有多少元素就有多少层
index:当前层我正要考虑的元素
index = length -1这个状态,正要考虑最后一个元素
index = length,这个状态才是考虑完所有元素的状态
one version(List version)
// Some code
public List<List<Integer>> subsets(int[] nums) {
List<List<Integer>> result = new ArrayList<>();
if (nums == null || nums.length == 0) {
return result;
}
List<Integer> current = new ArrayList<>();
backTracking(result, nums, current, 0);
return result;
}
// index我们当前层考虑的元素
private void backTracking(List<List<Integer>> result, int[] nums, List<Integer> current, int index) {
if (index == nums.length) {
result.add(new ArrayList<>(current));
return;
}
// add
current.add(nums[index]);
backTracking(result, nums, current, index + 1);
current.remove(current.size() - 1);
backTracking(result, nums, current, index + 1);
}another version (String version)
Question to deep dive: 能不能先写这个不加,这样是不是就可以不用吐了
万万不可
吃吐必须守恒,就算没有显示的吐,也一定通过某种方式达到吐的效果,直接吃掉吐又没有做任何补充,肯定不对!
原因是什么?在一个path上visited过的不能再visited?
Method 2:一个一个加(每一层是元素有几个,像permutation)
Step 1: 什么是一个解?一个subset就是一个解(题目让你做什么)
Step 2:如何构造一个subset
每一层:考虑这一层所有可以加的元素
分支:这一层把谁加进来
在哪里收集解:哪里都是解
相当于人为的自己加一个order:为了保证不发生由于顺序带来的重复
TC &SC: O(2^n), O(n)
one version(List version)
another version (String version)
PreviousGraph Theory XIV DFS3 Backtracking II Combination and PermutationNextProblem 2 Subset II with duplication
Last updated