Skip to content

491. Non-decreasing Subsequences 👍

  • Time: $O(n \cdot 2^n)$
  • Space: $O(n^2)$
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
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.contains(nums[i]))
        continue;
      if (path.empty() || nums[i] >= path.back()) {
        used.insert(nums[i]);
        path.push_back(nums[i]);
        dfs(nums, i + 1, std::move(path), ans);
        path.pop_back();
      }
    }
  }
};
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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();
      }
    }
  }
}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
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