代码随想录刷题Day29 | 491.递增子序列 | 46.全排列 | 47.全排列 II
491.递增子序列
题目:
给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是2。
示例:
- 输入: [4, 6, 7, 7]
- 输出: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
说明:
- 给定数组的长度不会超过15。
- 数组中的整数范围是 [-100,100]。
- 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
思路:
在图中可以看出,同一父节点下的同层上使用过的元素就不能在使用了,那么我们使用一个数组来标记已经使用过的元素
代码:
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;
}
public void backTracking(int[] nums, int start){
if(path.size() > 1){
result.add(new ArrayList<>(path));
}
int[] used = new int[210];
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);
}
}
}
46.全排列
题目:
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
- 输入: [1,2,3]
- 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
思路:
排列问题需要一个used数组,标记已经选择的元素,如图橘黄色部分所示:
- 每层都是从0开始搜索而不是startIndex
- 需要used数组记录path里都放了哪些元素
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int[] record = new int[6];
public List<List<Integer>> permute(int[] nums) {
backTracking(nums);
return result;
}
public void backTracking(int[] nums){
if(path.size() == nums.length){
result.add(new ArrayList<>(path));
return;
}
for(int i = 0; i < nums.length; i++){
if(record[i] == 1){
continue;
}
path.add(nums[i]);
record[i] = 1;
backTracking(nums);
path.remove(path.size() - 1);
record[i] = 0;
}
}
}
47.全排列 II
题目:
给定一个可包含重复数字的序列 nums ,按任意顺序 返回所有不重复的全排列。
示例 1:
- 输入:nums = [1,1,2]
- 输出: [[1,1,2], [1,2,1], [2,1,1]]
示例 2:
- 输入:nums = [1,2,3]
- 输出:[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
提示:
- 1 <= nums.length <= 8
- -10 <= nums[i] <= 10
思路:
这道题目和上题的区别在与给定一个可包含重复数字的序列,要返回所有不重复的全排列。
这里又涉及到去重了
代码:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
int[] record = new int[8];
public List<List<Integer>> permuteUnique(int[] nums) {
Arrays.sort(nums);
backTracking(nums);
return result;
}
public void backTracking(int[] nums){
if(path.size() == nums.length){
result.add(new ArrayList<>(path));
return;
}
int[] record1 = new int[21];
for(int i = 0; i < nums.length; i++){
if(record[i] == 1 || (i > 0 && record1[nums[i] + 10] == 1)){
continue;
}
record1[nums[i] + 10] = 1;
path.add(nums[i]);
record[i] = 1;
backTracking(nums);
path.remove(path.size() - 1);
record[i] = 0;
}
}
}