491. 递增子序列
leetcode上本题叫做非递减子序列,点名序列存在重复元素的情况。
class Solution {private List<Integer> path = new ArrayList<>();private List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> findSubsequences(int[] nums) {backtracking(nums,0);return res;}private void backtracking (int[] nums, int start) {if (path.size() > 1) {res.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]);backtracking(nums, i + 1);path.remove(path.size() - 1);}}
}
- res.add(new ArrayList<>(path));之后不要return,因为要添加树上的所有路径;
- 用数组used代替hash表,作用时表明等于x的数是否被用过,而不是x是否被用过(去重);
- nums[i] < path.get(path.size() - 1)约束出来的是递增子序列;
- 这里不需要used[nums[i] + 100] = 1;因为used每次都会初始化(注意不是成员变量)。
46.全排列
class Solution {private List<List<Integer>> resList = new ArrayList<>();private List<Integer> res = new ArrayList<>();private boolean[] used ;private void backtracking(int[] candidates, int startIndex){if(res.size() == candidates.length){resList.add(new ArrayList<>(res));return;}for(int i = 0; i < candidates.length; i++){if(!used[i]){res.add(candidates[i]);used[i] = true;backtracking(candidates, i);res.remove(res.size() - 1);used[i] = false;}}}public List<List<Integer>> permute(int[] nums) {used = new boolean[nums.length];backtracking(nums, 0);return resList;}
}
- 与组合不同的是排列有顺序,因此不需要startIndex,但不能选自身,所以用used数组。
47. 全排列II
class Solution {private List<List<Integer>> resList = new ArrayList<>();private List<Integer> res = new ArrayList<>();private boolean used[];private void backtracking(int[] candidates, int startIndex) {if (res.size() == candidates.length) {resList.add(new ArrayList<>(res));return;}for (int i = 0; i < candidates.length; i++) {if(i > 0 && candidates[i-1] == candidates[i] && !used[i - 1]){continue;}if(used[i] == false){used[i] = true;res.add(candidates[i]);backtracking(candidates, i);res.remove(res.size() - 1);used[i] = false;}}}public List<List<Integer>> permuteUnique(int[] nums) {used = new boolean[nums.length];Arrays.sort(nums);backtracking(nums, 0);return resList;}
}