递增子序列
给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是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]。
- 给定数组中可能包含重复数字,相等的数字应该被视为递增的一种情况。
https://leetcode.cn/problems/non-decreasing-subsequences/
重点:包含重复数字
需要去重
题目中说了,数值范围[-100,100],所以完全可以用数组来做哈希。
static List<List<Integer>> result=new ArrayList<>();
static List<Integer> path =new ArrayList<>();
public static List<List<Integer>> findSubsequences(int[] nums) {
tracking(nums,0);
return result;
}
private static void tracking(int[] nums,int startIndex){
if (path.size()>=2){
result.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]);
tracking(nums,i+1);
path.remove(path.size()-1);
}
}
全排列
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
示例:
- 输入: [1,2,3]
- 输出: [ [1,2,3], [1,3,2], [2,1,3], [2,3,1], [3,1,2], [3,2,1] ]
https://leetcode.cn/problems/permutations/
static List<List<Integer>> result=new ArrayList<>();
static LinkedList<Integer> path = new LinkedList<>();
static boolean[] used;
public static List<List<Integer>> permute(int[] nums) {
if (nums.length == 0){
return result;
}
used=new boolean[nums.length];
tracking(nums);
return result;
}
private static void tracking(int[] nums){
if (path.size()==nums.length){
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
if (used[i]){
continue;
}
used[i]=true;
path.add(nums[i]);
tracking(nums);
path.removeLast();
used[i]=false;
}
}
全排列 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
https://leetcode.cn/problems/permutations-ii/
去重一定前,先元素进行排序,方便通过相邻的节点来判断是否重复使用了
static List<List<Integer>> result=new ArrayList<>();
static LinkedList<Integer> path = new LinkedList<>();
public static List<List<Integer>> permute(int[] nums) {
boolean[] used=new boolean[nums.length];
Arrays.fill(used, false);//填充数组
Arrays.sort(nums);
tracking(nums,used);
return result;
}
//数层和树枝都要去重
private static void tracking(int[] nums,boolean[] used){
if (path.size()==nums.length){
result.add(new ArrayList<>(path));
return;
}
for (int i = 0; i < nums.length; i++) {
//nums[i] == nums[i - 1] && used[i - 1] == false 说明同⼀树层nums[i - 1]使⽤过
if (i > 0 && nums[i] == nums[i - 1] && used[i - 1] == false){
continue;
}
// used[i - 1] == true,说明同⼀树⽀nums[i - 1]使⽤过
if (used[i]==false){
used[i]=true;//防止同一树枝重复使用
path.add(nums[i]);
tracking(nums,used);
path.removeLast();//回溯
used[i]=false;
}
}
}