Leetcode 491.递增子序列
题目链接
思路:递归算法,去重
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums, 0);
return result;
}
private void backtracking(int[] nums, int startIndex) {
if (path.size() > 1) {
result.add(new ArrayList<>(path));
}
Set<Integer> set = new HashSet<>();
for (int i = startIndex; i < nums.length; i++) {
if (!path.isEmpty() && nums[i] < path.get(path.size() - 1) || set.contains(nums[i])) {
continue;
}
path.add(nums[i]);
set.add(nums[i]);
backtracking(nums, i + 1);
// 回溯
// set用于存放每层递归的元素,所以set不用回溯
path.remove(path.size() - 1);
}
}
}
Leetcode 46.全排列
题目链接
思路:回溯算法,全排列问题
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length];
Arrays.fill(used, false);
backtracking(nums, used);
return result;
}
private void backtracking(int[] nums, boolean[] used) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i] == true) {
continue;
}
path.add(nums[i]);
used[i] = true;
backtracking(nums, used);
// 回溯
path.remove(path.size() - 1);
used[i] = false;
}
}
}
Leetcode 47.全排列 II
题目链接
思路:回溯算法,全排列中有重复元素问题
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
used = new boolean[nums.length];
Arrays.fill(used, false);
Arrays.sort(nums);
backtracking(nums, used);
return result;
}
private void backtracking(int[] nums, boolean[] used) {
if (path.size() == nums.length) {
result.add(new ArrayList<>(path));
}
for (int i = 0; i < nums.length; i++) {
// 树层去重
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false) {
continue;
}
// 树枝去重
if (used[i] == true) {
continue;
}
path.add(nums[i]);
used[i] = true;
backtracking(nums, used);
// 回溯
path.remove(path.size() - 1);
used[i] = false;
}
}
}