491.递增子序列
1.题目:
给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例 1:
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
示例 2:
输入:nums = [4,4,3,2,1]
输出:[[4,4]]
https://leetcode.cn/problems/non-decreasing-subsequences
2.思路:
递归终止条件:遇到大于两个元素的就可以放入res,
单层递归:
每层使用HashSet来看是否有重复的元素。后一个加入元素要比path的最后一大,才可以加入。
3.代码:
class Solution {
//回溯
List<List<Integer>> res=new ArrayList<>();
List<Integer> path=new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums,0);
return res;
}
public void backtracking(int[] nums,int startIndex){
if(path.size()>=2){
res.add(new ArrayList<>(path));
}
HashSet<Integer> hs=new HashSet<>();
for(int i=startIndex;i<nums.length;i++){
if(path.size()>0 && nums[i]<path.get(path.size()-1)){
continue;
}
if(hs.contains(nums[i])){
continue;
}
hs.add(nums[i]);
path.add(nums[i]);
backtracking(nums,i+1);
path.remove(path.size()-1);
}
}
}
4.总结:
46.全排列
1.题目:
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
示例 1:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
示例 2:
输入:nums = [0,1]
输出:[[0,1],[1,0]]
https://leetcode.cn/problems/permutations
2.思路:
对于排列问题:要明确,不需要startIndex来记录递归到那个元素,因为组合是无序,排列是有序的。
每次递归还要去重,通过used数据记录path数组里的元素是否使用过
3.代码:
class Solution {
List<List<Integer>> res=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);
return res;
}
public void backtracking(int[] nums){
if(path.size()==nums.length){
res.add(new ArrayList<>(path));
}
for(int i=0;i<nums.length;i++){
if(used[i]){
continue;
}
used[i]=true;
path.add(nums[i]);
backtracking(nums);
path.remove(path.size()-1);
used[i]=false;
}
}
}
4.总结:
47.全排列 II
1.题目:
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
输入:nums = [1,1,2]
输出:
[[1,1,2],
[1,2,1],
[2,1,1]]
示例 2:
输入:nums = [1,2,3]
输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
https://leetcode.cn/problems/permutations-ii
2.思路:
去重: 同一层去重,同时每次递归还要去重,通过used数据记录path数组里的元素是否使用过
3.代码:
class Solution {
List<List<Integer>> res=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);
permutehepler(nums);
return res;
}
public void permutehepler(int[] nums){
if(nums.length==path.size()){
res.add(new ArrayList<>(path));
return ;
}
for(int i=0;i<nums.length;i++){
if(i>0&&nums[i]==nums[i-1]&&!used[i-1]){
continue;
}
if(used[i]==false){
used[i]=true;
path.add(nums[i]);
permutehepler(nums);
path.remove(path.size()-1);
used[i]=false;
}
}
}
}
4.总结: