LeetCode Solutions
491. Increasing Subsequences
Time: $O(n \cdot 2^n)$ Space: $O(n^2)$
class Solution {
public:
vector<vector<int>> findSubsequences(vector<int>& nums) {
vector<vector<int>> ans;
dfs(nums, 0, {}, ans);
return ans;
}
private:
void dfs(const vector<int>& nums, int s, vector<int>&& path,
vector<vector<int>>& ans) {
if (path.size() > 1)
ans.push_back(path);
unordered_set<int> used;
for (int i = s; i < nums.size(); ++i) {
if (used.count(nums[i]))
continue;
if (path.empty() || nums[i] >= path.back()) {
used.insert(nums[i]);
path.push_back(nums[i]);
dfs(nums, i + 1, move(path), ans);
path.pop_back();
}
}
}
};
class Solution {
public List<List<Integer>> findSubsequences(int[] nums) {
List<List<Integer>> ans = new LinkedList<>();
dfs(nums, 0, new LinkedList<>(), ans);
return ans;
}
private void dfs(int[] nums, int s, LinkedList<Integer> path, List<List<Integer>> ans) {
if (path.size() > 1)
ans.add(new LinkedList<>(path));
Set<Integer> used = new HashSet<>();
for (int i = s; i < nums.length; ++i) {
if (used.contains(nums[i]))
continue;
if (path.isEmpty() || nums[i] >= path.getLast()) {
used.add(nums[i]);
path.addLast(nums[i]);
dfs(nums, i + 1, path, ans);
path.removeLast();
}
}
}
}
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
ans = []
def dfs(s: int, path: List[int]) -> None:
if len(path) > 1:
ans.append(path)
used = set()
for i in range(s, len(nums)):
if nums[i] in used:
continue
if not path or nums[i] >= path[-1]:
used.add(nums[i])
dfs(i + 1, path + [nums[i]])
dfs(0, [])
return ans