We are given an integer array nums
. The task is to 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.
Input: nums = [4, 6, 7, 7]
Output: [[4, 6], [4, 6, 7], [4, 6, 7, 7], [4, 7], [4, 7, 7], [6, 7], [6, 7, 7], [7, 7]]
1 <= nums.length <= 15
#include <vector>
#include <set>
using namespace std;
class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
set<vector<int>> resultSet; // Using set to handle duplicates
vector<int> temp; // Temporary storage for the current subsequence
backtrack(nums, 0, temp, resultSet);
// Convert the set resultSet to a vector of vectors
return vector<vector<int>>(resultSet.begin(), resultSet.end());
}
private:
void backtrack(const vector<int>& nums, int start, vector<int>& temp, set<vector<int>>& resultSet) {
if (temp.size() >= 2) {
resultSet.insert(temp); // Only insert if we have a valid subsequence of at least length 2
}
for (int i = start; i < nums.size(); ++i) {
if (temp.empty() || nums[i] >= temp.back()) {
temp.push_back(nums[i]); // Include nums[i] in the subsequence
backtrack(nums, i + 1, temp, resultSet); // Continue exploring from the next position
temp.pop_back(); // Backtrack, remove the last element, and try another possibility
}
}
}
};
This backtracking approach ensures that we explore all possible non-decreasing subsequences and leverage a set to avoid duplicates.
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?