491. 递增子序列
- 学习文章链接:
- 思路:在子集的基础上去增加判断条件,即判断是否递增。
- 代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtracing(nums, 0);
return res;
}
public void backtracing(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;
used[nums[i] + 100] = 1;
path.add(nums[i]);
backtracing(nums, i + 1);
path.removeLast();
}
}
}
46.全排列
- 学习文章链接:
- 思路:注意两点:
- return的使用,详情见注释。
- used数组的使用。
- 代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> permute(int[] nums) {
boolean[] used = new boolean[nums.length];
backtracing(nums, used);
return res;
}
public void backtracing(int[] nums, boolean[] used) {
if (path.size() == nums.length) {
res.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i] == true) continue;
used[i] = true;
path.add(nums[i]);
backtracing(nums, used);
used[i] = false;
path.removeLast();
}
}
}
47.全排列 II
- 学习文章链接:
- 思路:基于全排列的基础上进行,不同的是,这里增加了重复元素,记得要排序哦。
- 代码:
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
boolean[] used = new boolean[nums.length];
backtracking(nums, used);
return res;
}
public void backtracking(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]);
backtracking(nums, used);
used[i] = false;
path.removeLast();
}
}
}
}