给定一个整型数组, 你的任务是找到所有该数组的递增子序列,递增子序列的长度至少是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<Integer> path = new ArrayList<>();
List<List<Integer>> ans = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
if (nums == null || nums.length == 0) {
return ans;
}
backtracking(nums, 0);
return ans;
}
private void backtracking(int[] nums, int start) {
// 对于当前的路径,根据题目要求,递增子序列的长度至少是 2,
// 因此,当前路径的长度大于等于 2 的时候,我就开始收集结果
if (path.size() >= 2) {
ans.add(new ArrayList<>(path));
}
HashSet<Integer> set = new HashSet<>();
for (int i = start; i < nums.length; i++) {
// 在 path 中含有元素的情况下,
// 如果当前遍历到的 nums[i] 比 path 中最后添加的那个元素要小的话,
// 那么就构不成递增序列,此时直接 continue。
// 同时,如果 set 已经存在了当前 nums[i] 的话,
// 那么我们也是不考虑的
if (path.size() > 0 && nums[i] < path.get(path.size() - 1)
|| set.contains(nums[i])) {
continue;
}
path.add(nums[i]);
set.add(nums[i]);
// 这里需要注意的是:
// 应该是 i + 1,而不是 start + 1
backtracking(nums, i + 1);
// 回溯操作
path.remove(path.size() - 1);
}
}
}
class Solution {
List<Integer> temp=new ArrayList<>();
List<List<Integer>> ans=new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
backtrace(nums,0,Integer.MIN_VALUE);
return ans;
}
public void backtrace(int[] nums,int cur,int last){
if( cur >= nums.length){
if(temp.size()>=2){
ans.add(new ArrayList<>(temp));
}
return ;
}
if(nums[cur]>=last){
temp.add(nums[cur]);
backtrace(nums,cur+1,nums[cur]);
temp.remove(temp.size()-1);
}
if(nums[cur]!=last)
backtrace(nums,cur+1,last);
}
}