题目:
Given an integer array nums
, return all the different possible increasing subsequences of the given array with at least two elements. You may return the answer in any order.
The given array may contain duplicates, and two equal integers should also be considered a special case of increasing sequence.
Example 1:
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]]
Example 2:
Input: nums = [4,4,3,2,1] Output: [[4,4]]
Constraints:
1 <= nums.length <= 15
-100 <= nums[i] <= 100
思路:
递归的base case是直到字符串的末尾。而加入的case是只要是两个以上的子串即可。显然在[4, 6, 7, 7]中会有两个[4, 6, 7],如果把递归看作树的话,我们要消除的是同一层递归的两个7,而保留同一条路径上的两个7,即[4, 7, 7]和[6, 7, 7]。那么在每一轮递归的时候, 使用一个哈希set来记录是否使用过某一个数字即可,剩下的就是标准回溯了。
代码:
class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
backtracking(nums, 0);
return res;
}
private:
vector<vector<int>> res;
vector<int> path;
void backtracking(vector<int>& nums, int index) {
if (path.size() > 1)
res.push_back(path);
if (index == nums.size())
return;
unordered_set<int> record;
for (int i = index; i < nums.size(); i++) {
if (path.size() == 0 || nums[i] >= path.back()) {
if (!record.count(nums[i])) {
path.push_back(nums[i]);
record.insert(nums[i]);
backtracking(nums, i + 1);
path.pop_back();
}
}
}
}
};