Problem 1 Subset I (combination)母题
Method 1: 加或者不加(只对combination问题有效) ==》 要么要么
// 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);
}Method 2:一个一个加(每一层是元素有几个,像permutation)
PreviousGraph Theory XIV DFS3 Backtracking II Combination and PermutationNextProblem 2 Subset II with duplication
Last updated