leetcode 491
题目链接
求递增子序列
思路:
- 求非递减的子序列 (non-decreasing subsequences),看上去有点类似于求子集,事实上不一样
- 可以看作一个DFS,也可以说是一个回溯
- think树层去重如何实现
- 用
set
容器,HashSet
- 用数组代替
hashset
, ∵ \because ∵ 元素的范围有限定-100 <= nums[i] <= 100
,想到用数组代替set
- 用
需要注意只是树层去重,每次递归/深度+1时都要定义一个新的数组
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums, 0);
return res;
}
private void backtracking(int[] nums, int index) {
if (path.size() > 1)
res.add(new ArrayList<>(path));
//nums[i]范围[-100, 100], flag用来记录这一次某数是否出现过, 树层去重
boolean[] flag = new boolean[201];
for (int i = index; i < nums.length; ++i) {
//1. path非空且当前元素不满足非递减了; 2. 树层重复了
if ((!path.isEmpty() && nums[i] < path.getLast()) || flag[nums[i] + 100])
continue;
flag[nums[i] + 100] = true;
path.add(nums[i]);
backtracking(nums, i + 1);
path.removeLast();
}
}
}
leetcode 46
题目链接
求一个数组的全排列 permutations
思路:
- 注意排列和组合的区别
for
横向遍历,注意每次递归startIndex
是什么- 用
Used数组
记录是否在该层用过了
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
boolean[] flag = new boolean[nums.length];
backtracking(nums, flag);
return res;
}
private void backtracking(int[] nums, boolean[] flag) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (flag[i])
continue;
path.add(nums[i]);
flag[i] = true;
backtracking(nums, flag);
path.removeLast();
flag[i] = false;
}
}
}
leetcode 47
题目链接
求一个数组的全排列 permutations,数组中可以有重复元素
思路:
- like leetcode 47,但要处理重复元素
- 树层去重
class Solution {
List<List<Integer>> res = new ArrayList<List<Integer>>();
Deque<Integer> path = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
boolean[] flag = new boolean[nums.length];
backtracking(nums, flag);
return res;
}
private void backtracking(int[] nums, boolean[] flag) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (i > 0 && nums[i] == nums[i - 1] && !flag[i - 1])
continue;
if (flag[i])
continue;
path.add(nums[i]);
flag[i] = true;
backtracking(nums, flag);
path.removeLast();
flag[i] = false;
}
}
}