代码随想录算法训练营第29天 | 491.递增子序列,46. 全排列,47. 全排列 II
491.递增子序列
- 子集问题 不需要终止条件 因为每个节点都要加入 所以每层递归最上面直接加入结果集就行了 或者加个判断条件
- 对于不能改变数组顺序的情况 就每次循环更新一次 map map不能定义在外面 这样上次循环的值还在Map中
- 对于递增的条件 每次加入元素前比较大小
- 假如不符合情况continue而不是break 因为后面可能还有符合情况的值
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracing(nums,0);
return result;
}
public void backtracing(int[] nums,int startIndex){
if(path.size()>1){
result.add(new ArrayList<>(path));
}
Map<Integer,Integer> map = new HashMap<>();
for(int i=startIndex;i<nums.length;i++){
if(!path.isEmpty() && nums[i]<path.get(path.size()-1)){
continue;
}
if(map.getOrDefault(nums[i],0)>0){
continue;
}
map.put(nums[i],map.getOrDefault(nums[i],0)+1);
path.add(nums[i]);
backtracing(nums,i+1);
path.remove(path.size()-1);
}
return;
}
}
46. 全排列
- 此题需要遍历全部数组 因此不用startindex 而是需要一个记录元素是否用过
- 当递归到叶节点也就是 path长度与num一样结束
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.fill(used,false);
backtracing(nums,used);
return result;
}
public void backtracing(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;
}
used[i]=true;
path.add(nums[i]);
backtracing(nums,used);
path.remove(path.size()-1);
used[i] = false;
}
return;
}
}
47. 全排列 II
- 此题树枝去重也可以得到答案 因为是排列问题 但是效率差 因为还要无用搜索
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.fill(used,false);
Arrays.sort(nums);
backtracing(nums,used);
return result;
}
public void backtracing(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 && used[i-1]==false && nums[i]==nums[i-1]){
continue;
}
if(used[i]==false){
used[i]=true;
path.add(nums[i]);
backtracing(nums,used);
used[i]=false;
path.remove(path.size()-1);
}
}
return;
}
}