[LeetCode] Increasing Subsequences

491. Increasing Subsequences

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.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>> res;
int n = nums.size();
for(int i = 0; i < n - 1; i++) {
vector<vector<int>> cur;
cur.push_back({nums[i]});
auto sorting = [](const vector<int>& a, const vector<int>& b) {return a.back() == b.back() ? a.size() < b.size() : a.back() < b.back(); };
for(int j = i + 1; j < n; j++) {
int sz = cur.size();
for(int k = 0; k < sz and cur[k].back() <= nums[j]; k++) {
vector<int> NEW(cur[k].begin(), cur[k].end());
NEW.push_back(nums[j]);
cur.push_back(NEW);
}
sort(cur.begin(), cur.end(), sorting);
}
res.insert(res.end(), cur.begin() + 1, cur.end());
}
set<vector<int>> filter(res.begin(), res.end());
return vector<vector<int>> (filter.begin(),filter.end());
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/01/31/PS/LeetCode/increasing-subsequences/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.