非递减子序列
List<List<Integer>> res=new ArrayList<List<Integer>>();
LinkedList<Integer> path=new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
trackBack(nums,0);
return res;
}
public void trackBack(int[] nums,int index){
if(path.size()>=2){
res.add(new ArrayList<>(path));
}
HashMap<Integer,Integer> map = new HashMap<>();
for(int i=index;i<nums.length;i++){
if(!path.isEmpty()&&path.getLast()>nums[i])continue;
if(map.getOrDefault(nums[i],0)>=1)continue;
map.put(nums[i],map.getOrDefault(nums[i],0)+1);
path.add(nums[i]);
trackBack(nums,i+1);
path.removeLast();
}
}
全排列
List<List<Integer>> res=new ArrayList<List<Integer>>();
LinkedList<Integer> path=new LinkedList<Integer>();
boolean []used;
public List<List<Integer>> permute(int[] nums) {
used=new boolean[nums.length];
trackBack(nums);
return res;
}
public void trackBack(int[] nums){
if(path.size()==nums.length) res.add(new ArrayList<>(path));
for(int i=0;i<nums.length;i++){
if(used[i])continue;
path.add(nums[i]);
used[i]=true;
trackBack(nums);
used[i]=false;
path.removeLast();
}
}
全排列 II
List<List<Integer>> res=new ArrayList<List<Integer>>();
LinkedList<Integer> path=new LinkedList<Integer>();
boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
used=new boolean[nums.length];
Arrays.sort(nums);
trackback(nums);
return res;
}
public void trackback(int[]nums){
if(path.size()==nums.length){
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]==false)continue;
if(used[i]==false){
path.add(nums[i]);
used[i]=true;
trackback(nums);
path.removeLast();
used[i]=false;
}
}
}
重新安排行程
LinkedList<String> res;
LinkedList<String>path=new LinkedList<>();
public List<String> findItinerary(List<List<String>> tickets) {
Collections.sort(tickets,(a,b)->a.get(1).compareTo(b.get(1)));
path.add("JFK");
boolean []used=new boolean[tickets.size()];
backTrack((ArrayList)tickets,used);
return res;
}
public boolean backTrack(ArrayList<List<String>>tickets,boolean[]used){
if(path.size()==tickets.size()+1){
res=new LinkedList(path);
return true;
}
for(int i=0;i<tickets.size();i++){
if(!used[i]&&tickets.get(i).get(0).equals(path.getLast())){
path.add(tickets.get(i).get(1));
used[i]=true;
if(backTrack(tickets,used)){
return true;
}
used[i]=false;
path.removeLast();
}
}
return false;
}
超过了时间限制