Given an integer array nums
, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.
import java.util.*;
public class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
Set<List<Integer>> result = new HashSet<>();
List<Integer> tempList = new ArrayList<>();
backtrack(result, tempList, nums, 0);
return new ArrayList<>(result);
}
private void backtrack(Set<List<Integer>> result, List<Integer> tempList, int[] nums, int start) {
if (tempList.size() >= 2) {
result.add(new ArrayList<>(tempList));
}
for (int i = start; i < nums.length; i++) {
if (tempList.isEmpty() || nums[i] >= tempList.get(tempList.size() - 1)) {
tempList.add(nums[i]);
backtrack(result, tempList, nums, i + 1);
tempList.remove(tempList.size() - 1);
}
}
}
public static void main(String[] args) {
Solution solution = new Solution();
int[] nums = {4, 6, 7, 7};
System.out.println(solution.findSubsequences(nums));
}
}
O(2^n)
, where n
is the length of the input array. For each element, we decide to include it in the current subsequence or not, which leads to exponential combinations.O(n * 2^n)
for storing the subsequences and for the recursion stack.This solution efficiently finds all non-decreasing subsequences by exploring all potential subsequences through a backtracking approach. The usage of a set ensures that duplicate subsequences are filtered out.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?