MediumNo. 0491

Non-decreasing Subsequences — LeetCode 491 Python Solution

Topics
Bit Manipulation, Array, Hash Table, Backtracking
Reading time
3 min

The problem

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

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]]

Python solution

PythonSolution
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

Complexity

Time
O(n)
Space · auxiliary
O(n)

Pattern: Backtracking

Build candidates one choice at a time and abandon a branch the moment it cannot work. LeetCode 491. Non-decreasing Subsequences is filed here because LeetCode tags it Backtracking, which is the vocabulary this hub collects.

The backtracking guide has the Python template for the pattern and the 105 LeetCode problems that use it.

Related problems

Related problems
No.ProblemDifficulty
0691Stickers to Spell WordHard
0996Number of Squareful ArraysHard
1255Maximum Score Words Formed by LettersHard
0037Sudoku SolverHard
0140Word Break IIHard
0268Missing NumberEasy

Frequently asked questions

How hard is LeetCode 491. Non-decreasing Subsequences?

LeetCode 491. Non-decreasing Subsequences is rated Medium on LeetCode.

What is the time complexity of LeetCode 491. Non-decreasing Subsequences?

The Python solution on this page runs in O(n).

What is the space complexity of LeetCode 491. Non-decreasing Subsequences?

The Python solution on this page uses O(n) auxiliary space.

What topics does LeetCode 491. Non-decreasing Subsequences cover?

LeetCode 491. Non-decreasing Subsequences is tagged Bit Manipulation, Array, Hash Table and Backtracking on LeetCode.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity, invisible to screen sharing.

Free to download. Check it runs on your machine, then pick a plan.