Skip to content
LC-0491 Medium LeetCode

491. Non-decreasing Subsequences

Read the full problem statement on LeetCode.
Difficulty: medium Acceptance: 62% Topics: Array, Hash Table, Backtracking, Bit Manipulation
View full problem on LeetCode
Reference solution (spoiler · java)
import java.util.*;

class Solution {
    List<List<Integer>> findSubsequences(int[] nums) {
        List<List<Integer>> res = new ArrayList<>();
        dfs(nums, 0, new ArrayList<>(), res);
        return res;
    }
    private void dfs(int[] nums, int start, List<Integer> path, List<List<Integer>> res) {
        if (path.size() >= 2) res.add(new ArrayList<>(path));
        Set<Integer> used = new HashSet<>();
        for (int i = start; i < nums.length; i++) {
            if (!path.isEmpty() && nums[i] < path.get(path.size() - 1)) continue;
            if (used.contains(nums[i])) continue;
            used.add(nums[i]);
            path.add(nums[i]);
            dfs(nums, i + 1, path, res);
            path.remove(path.size() - 1);
        }
    }
}

Solution from kamyu104/LeetCode-Solutions · MIT