Non-decreasing Subsequences (LeetCode 491): Solution and Explanation
Return every distinct non-decreasing subsequence of nums with at least two elements, in any order. For [4,6,7,7] there are 8 of them, such as [4,6], [4,7,7] and [7,7]. The array cannot be sorted, because a subsequence must keep the original order.
Intuition
With at most 15 elements there are at most 2^15 subsequences, so building them all by backtracking is fine. The work is in avoiding duplicates.
Grow a path from left to right. A value may join only if it is at least the current last value, which keeps the path non-decreasing at every moment.
Duplicates come from picking equal values as the next element at the same depth: both choices lead to identical subtrees. A small set per recursive call that remembers which values already started a branch removes them, without sorting the input.
Approach: Backtracking with a per-depth used set
- Define
dfs(start). If the current path has at least two values, record a copy. - Create an empty
usedset for this call. - For each
ifromstartto the end: skipnums[i]if it is already inused, or if the path is non-empty andnums[i]is smaller than its last value. - Otherwise add
nums[i]toused, append it to the path, calldfs(i + 1), and pop it afterwards. - Call
dfs(0)and return the recorded list.
Step-by-step example
nums = [4,6,7,7]
- Depth 0 picks 4. Depth 1 picks 6, records [4,6], then picks 7 and records [4,6,7], then the last 7 gives [4,6,7,7].
- Back at depth 2 under [4,6], the second 7 is skipped because 7 is already in that depth's used set.
- Under [4] the branch with 7 gives [4,7] and [4,7,7]; the second 7 at that depth is skipped again.
- Starting from 6 gives [6,7] and [6,7,7]; starting from the first 7 gives [7,7]. The second 7 at depth 0 is skipped.
- Eight subsequences in total, with no duplicates.
Code: Python, Java, C++
1class Solution:
2 def findSubsequences(self, nums: List[int]) -> List[List[int]]:
3 res = []
4 path = []
5 def dfs(start):
6 if len(path) >= 2:
7 res.append(path[:])
8 used = set()
9 for i in range(start, len(nums)):
10 if nums[i] in used:
11 continue
12 if path and nums[i] < path[-1]:
13 continue
14 used.add(nums[i])
15 path.append(nums[i])
16 dfs(i + 1)
17 path.pop()
18 dfs(0)
19 return res1class Solution {
2 private List<List<Integer>> res = new ArrayList<>();
3 private List<Integer> path = new ArrayList<>();
4
5 public List<List<Integer>> findSubsequences(int[] nums) {
6 dfs(nums, 0);
7 return res;
8 }
9
10 private void dfs(int[] nums, int start) {
11 if (path.size() >= 2) {
12 res.add(new ArrayList<>(path));
13 }
14 Set<Integer> used = new HashSet<>();
15 for (int i = start; i < nums.length; i++) {
16 if (used.contains(nums[i])) {
17 continue;
18 }
19 if (!path.isEmpty() && nums[i] < path.get(path.size() - 1)) {
20 continue;
21 }
22 used.add(nums[i]);
23 path.add(nums[i]);
24 dfs(nums, i + 1);
25 path.remove(path.size() - 1);
26 }
27 }
28}1class Solution {
2public:
3 vector<vector<int>> findSubsequences(vector<int>& nums) {
4 vector<vector<int>> res;
5 vector<int> path;
6 dfs(nums, 0, path, res);
7 return res;
8 }
9
10 void dfs(vector<int>& nums, int start, vector<int>& path, vector<vector<int>>& res) {
11 if (path.size() >= 2) {
12 res.push_back(path);
13 }
14 unordered_set<int> used;
15 for (int i = start; i < (int) nums.size(); i++) {
16 if (used.count(nums[i])) {
17 continue;
18 }
19 if (!path.empty() && nums[i] < path.back()) {
20 continue;
21 }
22 used.insert(nums[i]);
23 path.push_back(nums[i]);
24 dfs(nums, i + 1, path, res);
25 path.pop_back();
26 }
27 }
28};Time and space complexity
O(2^n * n)
There are at most 2^n paths and copying one into the answer costs up to n.
O(n)
The recursion depth, the path and the used sets along one branch are O(n) each, not counting the output.
Other approaches
Bitmask enumeration with a global set (time O(2^n * n), space O(2^n * n))
Try all 2^n masks, keep the ones whose picked values are non-decreasing and have length 2 or more, and dedupe them through a set of tuples. Simple, but it does extra work on invalid masks.
Backtracking with a global result set (time O(2^n * n), space O(2^n * n))
Generate all valid paths and insert them into a hash set of tuples. It is correct but generates every duplicate before discarding it.
Common mistakes
- Sorting the input to group duplicates, as in Subsets II. Sorting changes which subsequences exist, so it gives wrong answers here.
- Sharing one used set across all depths. The set must be local to each call, otherwise valid paths such as [4,7,7] get blocked.
- Recording the path only at leaves. Every path of length 2 or more is an answer, so record it on entry to each call.
Frequently asked questions
Why is the per-depth set enough to remove all duplicates?
Two identical answers would have to differ in which index supplied some position. The first depth where they differ picks the same value from two indices, which the set at that depth forbids.
Can the used set be an array instead of a hash set?
Yes. Values lie in [-100, 100], so a boolean array of size 201 indexed by value + 100 works and is slightly faster.
Does the order of the output matter?
No. Any order is accepted, and the values inside each subsequence keep their order from nums.