Off-by-one on range boundaries
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Move from brute-force thinking to an efficient approach using array strategy.
Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.
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] <= 100Problem summary: Given an integer array nums, return all the different possible non-decreasing subsequences of the given array with at least two elements. You may return the answer in any order.
Start with the most direct exhaustive search. That gives a correctness anchor before optimizing.
Pattern signal: Array · Hash Map · Backtracking · Bit Manipulation
[4,6,7,7]
[4,4,3,2,1]
maximum-length-of-pair-chain)Source-backed implementations are provided below for direct study and interview prep.
// Accepted solution for LeetCode #491: Non-decreasing Subsequences
class Solution {
private int[] nums;
private List<List<Integer>> ans;
public List<List<Integer>> findSubsequences(int[] nums) {
this.nums = nums;
ans = new ArrayList<>();
dfs(0, -1000, new ArrayList<>());
return ans;
}
private void dfs(int u, int last, List<Integer> t) {
if (u == nums.length) {
if (t.size() > 1) {
ans.add(new ArrayList<>(t));
}
return;
}
if (nums[u] >= last) {
t.add(nums[u]);
dfs(u + 1, nums[u], t);
t.remove(t.size() - 1);
}
if (nums[u] != last) {
dfs(u + 1, last, t);
}
}
}
// Accepted solution for LeetCode #491: Non-decreasing Subsequences
func findSubsequences(nums []int) [][]int {
var ans [][]int
var dfs func(u, last int, t []int)
dfs = func(u, last int, t []int) {
if u == len(nums) {
if len(t) > 1 {
ans = append(ans, slices.Clone(t))
}
return
}
if nums[u] >= last {
t = append(t, nums[u])
dfs(u+1, nums[u], t)
t = t[:len(t)-1]
}
if nums[u] != last {
dfs(u+1, last, t)
}
}
var t []int
dfs(0, -1000, t)
return ans
}
# Accepted solution for LeetCode #491: Non-decreasing Subsequences
class Solution:
def findSubsequences(self, nums: List[int]) -> List[List[int]]:
def dfs(u, last, t):
if u == len(nums):
if len(t) > 1:
ans.append(t[:])
return
if nums[u] >= last:
t.append(nums[u])
dfs(u + 1, nums[u], t)
t.pop()
if nums[u] != last:
dfs(u + 1, last, t)
ans = []
dfs(0, -1000, [])
return ans
// Accepted solution for LeetCode #491: Non-decreasing Subsequences
struct Solution;
impl Solution {
fn find_subsequences(nums: Vec<i32>) -> Vec<Vec<i32>> {
let mut res: Vec<Vec<i32>> = vec![];
let n = nums.len();
let mut cur: Vec<i32> = vec![];
Self::dfs(0, &mut cur, &mut res, &nums, n);
res
}
fn dfs(start: usize, cur: &mut Vec<i32>, all: &mut Vec<Vec<i32>>, nums: &[i32], n: usize) {
if start == n {
if cur.len() > 1 {
all.push(cur.to_vec());
}
} else {
if cur.is_empty() || nums[start] >= *cur.last().unwrap() {
cur.push(nums[start]);
Self::dfs(start + 1, cur, all, nums, n);
cur.pop();
}
if cur.is_empty() || nums[start] != *cur.last().unwrap() {
Self::dfs(start + 1, cur, all, nums, n);
}
}
}
}
#[test]
fn test() {
let nums = vec![4, 6, 7, 7];
let mut res = vec_vec_i32![
[4, 6],
[4, 7],
[4, 6, 7],
[4, 6, 7, 7],
[6, 7],
[6, 7, 7],
[7, 7],
[4, 7, 7]
];
let mut ans = Solution::find_subsequences(nums);
res.sort();
ans.sort();
assert_eq!(ans, res);
}
// Accepted solution for LeetCode #491: Non-decreasing Subsequences
// Auto-generated TypeScript example from java.
function exampleSolution(): void {
}
// Reference (java):
// // Accepted solution for LeetCode #491: Non-decreasing Subsequences
// class Solution {
// private int[] nums;
// private List<List<Integer>> ans;
//
// public List<List<Integer>> findSubsequences(int[] nums) {
// this.nums = nums;
// ans = new ArrayList<>();
// dfs(0, -1000, new ArrayList<>());
// return ans;
// }
//
// private void dfs(int u, int last, List<Integer> t) {
// if (u == nums.length) {
// if (t.size() > 1) {
// ans.add(new ArrayList<>(t));
// }
// return;
// }
// if (nums[u] >= last) {
// t.add(nums[u]);
// dfs(u + 1, nums[u], t);
// t.remove(t.size() - 1);
// }
// if (nums[u] != last) {
// dfs(u + 1, last, t);
// }
// }
// }
Use this to step through a reusable interview workflow for this problem.
Generate every possible combination without any filtering. At each of n positions we choose from up to n options, giving nⁿ total candidates. Each candidate takes O(n) to validate. No pruning means we waste time on clearly invalid partial solutions.
Backtracking explores a decision tree, but prunes branches that violate constraints early. Worst case is still factorial or exponential, but pruning dramatically reduces the constant factor in practice. Space is the recursion depth (usually O(n) for n-level decisions).
Review these before coding to avoid predictable interview regressions.
Wrong move: Loop endpoints miss first/last candidate.
Usually fails on: Fails on minimal arrays and exact-boundary answers.
Fix: Re-derive loops from inclusive/exclusive ranges before coding.
Wrong move: Zero-count keys stay in map and break distinct/count constraints.
Usually fails on: Window/map size checks are consistently off by one.
Fix: Delete keys when count reaches zero.
Wrong move: Mutable state leaks between branches.
Usually fails on: Later branches inherit selections from earlier branches.
Fix: Always revert state changes immediately after recursive call.