491.递增子序列
思路
题解思路:重要的点在于,因为本身不是有序的,所以同层的去重中,需要去除跟之前相同的数字。
代码
class Solution {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracking(nums,0);
return results;
}
public void backtracking(int[] nums,int startIndex){
if(path.size()>1){
results.add(new ArrayList<Integer>(path));
}
Set set = new HashSet<Integer>();
for(int i = startIndex;i<nums.length;i++){
if(!path.isEmpty() && nums[i]<path.get(path.size()-1))
continue;
if(set.contains(nums[i]))
continue;
set.add(nums[i]);
path.add(nums[i]);
backtracking(nums,i+1);
path.remove(path.size()-1);
}
}
}
46.全排列
思路
全排列不需要startIndex,另外注意set的remove方法用法,它是删除掉指定元素。
代码
class Solution {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
Set set = new HashSet<Integer>();
public List<List<Integer>> permute(int[] nums) {
backtracking(nums);
return results;
}
public void backtracking(int[] nums){
if(path.size()==nums.length){
results.add(new ArrayList<Integer>(path));
return;
}
for(int i=0;i<nums.length;i++){
if(set.contains(nums[i])) continue;
set.add(nums[i]);
path.add(nums[i]);
backtracking(nums);
path.remove(path.size()-1);
set.remove(nums[i]);
}
}
}
47.全排列 II
思路
题解思路:其他跟前一道题类似, 关键是要记录某个变量同一树枝是否使用过,所以需要在递归的过程中,设置一个可以传递的局部变量,记录某个数字否使用过。 另外在同一层需要排除已经用过的重复的数字,所以需要预先排序。
这题的去重比较有意思。
代码
class Solution {
List<List<Integer>> results = new ArrayList<List<Integer>>();
List<Integer> path = new ArrayList<Integer>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
Boolean used[] = new Boolean[nums.length];
Arrays.fill(used,false);
backtracking(nums,used);
return results;
}
public void backtracking(int[] nums,Boolean used[]){
if(path.size()==nums.length){
results.add(new ArrayList<Integer>(path));
return;
}
for(int i=0;i<nums.length;i++){
if(i > 0 && nums[i]==nums[i-1] &&used[i-1]==true ) continue;//同一树层使用过同样的元素 跳过
if(used[i]==true) continue;//同一树枝使用过 所以跳过
used[i]=true;
path.add(nums[i]);
backtracking(nums,used);
path.remove(path.size()-1);
used[i]=false;
}
}
}