491.递增子序列
题目链接:491.递增子序列
文档讲解︰代码随想录(programmercarl.com)
视频讲解︰491.递增子序列
日期:2024-10-02
想法:根据题目nums[i]的范围在-100到100,可以用数组做记录是否同一层使用过
Java代码如下:
class Solution {
List<Integer> path = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
public void backTracking(int[] nums, int startIndex) {
if(path.size() > 1) {
res.add(new ArrayList<>(path));
}
int[] used = new int[201];
for(int i = startIndex; i < nums.length; i++) {
if(!path.isEmpty() && nums[i] < path.get(path.size() - 1) || (used[nums[i] + 100] == 1)) {
continue;
}
path.add(nums[i]);
used[nums[i] + 100] = 1;
backTracking(nums, i + 1);
path.removeLast();
}
}
public List<List<Integer>> findSubsequences(int[] nums) {
backTracking(nums, 0);
return res;
}
}
46.全排列
题目链接:46.全排列
文档讲解︰代码随想录(programmercarl.com)
视频讲解︰全排列
日期:2024-10-02
想法:注意点:全排列结果数组大小跟原数组相同, 遍历得从头开始,不需要startIndex了,不能重复使用元素用used数组
Java代码如下:
class Solution {
List<Integer> path = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
boolean[] used;
public void backTracking(int[] nums) {
if(path.size() == nums.length) {
res.add(new ArrayList<>(path));
}
for(int i = 0; i < nums.length; i++) {
if(used[i] == true) {
continue;
}
used[i] = true;
path.add(nums[i]);
backTracking(nums);
path.removeLast();
used[i] = false;
}
}
public List<List<Integer>> permute(int[] nums) {
used = new boolean[nums.length];
Arrays.fill(used, false);
backTracking(nums);
return res;
}
}
47.全排列 II
题目链接:47.全排列 II
文档讲解︰代码随想录(programmercarl.com)
视频讲解︰全排列 II
日期:2024-10-02
想法:加入同层去重,排列数组和i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false
Java代码如下:
class Solution {
List<Integer> path = new ArrayList<>();
List<List<Integer>> res = new ArrayList<>();
boolean[] used;
public void backTracking(int[] nums) {
if(path.size() == nums.length) {
res.add(new ArrayList<>(path));
}
for(int i = 0; i < nums.length; i++) {
if(i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false || used[i] == true) {
continue;
}
used[i] = true;
path.add(nums[i]);
backTracking(nums);
path.removeLast();
used[i] = false;
}
}
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
used = new boolean[nums.length];
Arrays.fill(used, false);
backTracking(nums);
return res;
}
}
标签:排列,nums,46,res,随想录,int,used,new,path
From: https://www.cnblogs.com/wowoioo/p/18444506