题目:
给你一个整数数组 nums ,找出并返回所有该数组中不同的递增子序列,递增子序列中 至少有两个元素 。你可以按 任意顺序 返回答案。
数组中可能含有重复元素,如出现两个整数相等,也可以视作递增序列的一种特殊情况。
示例 1:
输入:nums = [4,6,7,7]
输出:[[4,6],[4,6,7],[4,6,7,7],[4,7],[4,7,7],[6,7],[6,7,7],[7,7]]
示例 2:
输入:nums = [4,4,3,2,1]
输出:[[4,4]]
提示:
1 <= nums.length <= 15
-100 <= nums[i] <= 100
代码:
public class FindSubsequences {
// 491. 递增子序列
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> findSubsequences(int[] nums) {
List<Integer> tempList = new ArrayList<>();
findSubsequences(nums, 0, tempList);
return result;
}
public void findSubsequences(int[] nums, int begin, List<Integer> tempList) {
if (tempList.size() >= 2) {
result.add(new ArrayList<>(tempList));
}
for (int i = begin; i < nums.length; i++) {
int flag = 0;
for (int j = i - 1; j >= begin; j--) {
if (nums[i] == nums[j]) {
flag = 1;
break;
}
}
if (flag == 1 || begin > 0 && nums[i] < nums[begin - 1]) {
continue;
}
tempList.add(nums[i]);
findSubsequences(nums, i + 1, tempList);
tempList.remove(tempList.size() - 1);
}
}
public static void main(String[] args) {
//int[] nums = new int[]{4,6,7,7}; //[1,2,3,4,1,1]
int[] nums = new int[]{4, 4, 3, 2, 1};
FindSubsequences solution = new FindSubsequences();
List<List<Integer>> result = solution.findSubsequences(nums);
for (List<Integer> subList : result) {
for (int i : subList) {
System.out.print(i + " ");
}
System.out.print('\n');
}
}
}