491.递增子序列
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backTracking(nums, 0);
return result;
}
private void backTracking(int[] nums, int startIndex){
if(path.size() >= 2)
result.add(new ArrayList<>(path));
HashSet<Integer> hs = new HashSet<>();
for(int i = startIndex; i < nums.length; i++){
if(!path.isEmpty() && path.get(path.size() -1 ) > nums[i] || hs.contains(nums[i]))
continue;
hs.add(nums[i]);
path.add(nums[i]);
backTracking(nums, i + 1);
path.remove(path.size() - 1);
}
}
}
46.全排列
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
boolean[] used;
public List<List<Integer>> permute(int[] nums) {
if (nums.length == 0){
return res;
}
used = new boolean[nums.length];
test(nums);
return res;
}
public void test(int []nums){
if(path.size()==nums.length){
res.add(new ArrayList<Integer>(path));
return;
}
for(int i=0;i<nums.length;i++){
if(used[i]){
continue;
}
used[i] =true;
path.add(nums[i]);
test(nums);
path.removeLast();
used[i] = false;
}
}
}
47.全排列 II
通过uesd数组来进行判断前一个用过还是没用过,然后再通过used[i-1]来判断同一树层的数据是否使用过
class Solution {
List<Integer> path = new ArrayList<Integer>();
LinkedList<List<Integer>> res = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
boolean[] used = new boolean[nums.length];
Arrays.fill(used, false);
Arrays.sort(nums);
test(nums, used);
return res;
}
public void test(int nums[],boolean[] used){
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){
used[i]=true;
path.add(nums[i]);
test(nums,used);
path.remove(path.size()-1);
used[i]=false;
}
}
}
}
文章介绍了两种基于回溯法的算法实现,分别是寻找给定整数数组中的递增子序列和全排列,以及优化版本的全排列II,通过使用哈希集和used数组判断元素是否已使用。
974

被折叠的 条评论
为什么被折叠?



