一句话总结:去重操作不是很理解。
原题链接:491 非递减子序列
照着模板吭哧写就完事了。去重操作稍微难想点。
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
if (nums.length < 1) return ans;
backTrack(nums, 0);
return ans;
}
private void backTrack(int[] nums, int start) {
if (path.size() > 1) {
ans.add(new ArrayList<>(path));
}
int[] used = new int[201];
for (int i = start; 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]);
backTrack(nums, i + 1);
path.removeLast();
}
}
}
原题链接:46 全排列
还是个很好的套模板的题目,去重操作也并不复杂。
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> permute(int[] nums) {
int n = nums.length;
backtrack(nums);
return ans;
}
private void backtrack(int[] nums) {
if (path.size() == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (path.contains(nums[i])) continue;
path.add(nums[i]);
backtrack(nums);
path.removeLast();
}
}
}
原题链接:47 全排列II
主体还是套用模板,去重操作难一点,附原题解:题解 。
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
boolean[] used;
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
used = new boolean[nums.length];
backTrack(nums);
return ans;
}
private void backTrack(int[] nums) {
if (path.size() == nums.length) {
ans.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; ++i) {
if (i > 0 && nums[i] == nums[i - 1] && !used[i - 1]) continue;
if (!used[i]) {
used[i] = true;
path.add(nums[i]);
backTrack(nums);
path.removeLast();
used[i] = false;
}
}
}
}