Non-decreasing Subsequences — LeetCode 491 Python Solution
MediumBit ManipulationArrayHash TableBacktracking
- Problem
- #491
- Pattern
- Backtracking
- Reading time
- 3 min
- Source
- leetcode.com
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
Python
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 ansComplexity
| Measure | Complexity |
|---|---|
| Time | O(n) |
| Space | O(n) auxiliary |
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
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.