491. 递增子序列
题目描述
给定一个整型数组,你的任务是找到所有该数组的递增子序列,且递增子序列的长度至少是 2。
解题思路
算法分析
-
回溯法:
- 使用回溯的思想,从索引
startIndex开始,逐步构建递增子序列。 - 遇到满足条件的递增子序列时,将其添加到结果列表中。
- 使用回溯的思想,从索引
-
约束条件:
- 子序列是 非严格递增 的,因此允许重复元素。
- 使用一个
HashSet防止在同一层递归中处理相同数字,避免重复子序列的生成。
-
递归边界:
- 遍历到数组末尾后停止递归。
- 当子序列长度大于等于 2 时,将其加入结果列表。
代码实现
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() >= 2)
result.add(new ArrayList<>(path));
HashSet<Integer> hs = new HashSet<>();
for(int i = startIndex; i < nums.length; i++){
if(!path.isEmpty() && path.get(path.size() -1 ) > nums[i] || hs.contains(nums[i]))
continue;
hs.add(nums[i]);
path.add(nums[i]);
backTracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}
46. 全排列
题目描述
给定一个没有重复数字的序列,返回其所有可能的全排列。
解题思路
算法分析
-
回溯法:
- 使用回溯的思想,通过递归生成所有可能的排列。
- 每次递归时尝试选择未被使用的数字,将其加入当前排列路径中,直到路径长度等于数组长度。
-
约束条件:
- 使用一个布尔数组
used标记当前数字是否已经加入路径,避免重复选择。
- 使用一个布尔数组
-
递归边界:
- 当路径长度等于数组长度时,说明已经完成了一个全排列,将其加入结果列表。
代码实现
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
if(nums.length == 0){
return result;
}
used = new boolean[nums.length];
treebuilding(nums);
return result;
}
public void treebuilding(int[] nums) {
if(path.size() == nums.length){
result.add(new ArrayList<>(path));
return;
}
for(int i = 0;i< nums.length;i++){
if(used[i]){
continue;
}
used[i] = true;
path.add(nums[i]);
treebuilding(nums);
path.removeLast();
used[i] = false;
}
}
}
47.全排列 II
题目:给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
解题思路:
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.fill(used,false);
Arrays.sort(nums);
treebuilding(nums,used);
return result;
}
public void treebuilding(int[] nums,boolean[] used) {
if(path.size() == nums.length){
result.add(new ArrayList<>(path));
return;
}
for(int i = 0;i<nums.length;i++){
if(i>0 && nums[i]==nums[i-1] && used[i-1] == false){
continue;
}
if(used[i]==false){
used[i] = true;
path.add(nums[i]);
treebuilding(nums,used);
path.removeLast();
used[i] = false;
}
}
}
}
491.递增子序列
题目:
解题思路:
代码:
在这里插入代码片
491.递增子序列
题目:
解题思路:
代码:
在这里插入代码片
491.递增子序列
题目:
解题思路:
代码:
在这里插入代码片
323

被折叠的 条评论
为什么被折叠?



