491.递增子序列
第一次没咋看思路 一遍过的medium 记录下!!
重点是知道树层中不能有重复的,所以每一个递归中需要个HashMap记录用没用过一个元素
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
if(nums.length == 0 || nums == null)return result;
backtrack(nums,0);
return result;
}
private void backtrack(int[] nums, int startIndex){
Map<Integer,Integer> map = new HashMap<>();
if(path.size() >= 2){
result.add(new ArrayList<>(path));
}
for(int i = startIndex; i < nums.length; i++){
Integer value = map.get(nums[i]);
if((path.size()>0 && path.get(path.size()-1) > nums[i]) || (value != null && value > 0)){
continue;
}else{
path.add(nums[i]);
map.put(nums[i],map.getOrDefault(nums[i],0)+1);
backtrack(nums,i+1);
path.removeLast();
}
}
}
}
46.全排列
没看代码随想录自己写的,效率有点低 时间复杂度高了
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
if(nums.length == 0 || nums == null)return result;
backtrack(nums);
return result;
}
private void backtrack(int[] nums){
if(path.size() == nums.length){
result.add(new ArrayList<>(path));
}
for(int i = 0; i < nums.length; i++){
int exist = 0;
for(int eachone : path){
if(nums[i] == eachone){
exist = 1;
}
}
if(exist == 1)continue;
path.add(nums[i]);
backtrack(nums);
path.removeLast();
}
}
}
47.全排列 II
class Solution {
List<List<Integer>> result = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
if(nums.length == 0 || nums == null)return result;
boolean[] used = new boolean[nums.length];
Arrays.fill(used,false);
Arrays.sort(nums);
backtrack(nums,used);
return result;
}
private void backtrack(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){
path.add(nums[i]);
used[i] = true;
backtrack(nums,used);
path.removeLast();
used[i] = false;
}
}
}
}