LeetCode491. Non-decreasing Subsequences

文章目录

一、题目

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 <= numsi <= 100

二、题解

既可以使用unordered_map进行判断是否在同一层上有重复元素,也可以使用unordered_set进行去重

cpp 复制代码
class Solution {
public:
    vector<int> path;
    vector<vector<int>> res;
    void backtracking(vector<int>& nums,int startIndex){
        if(path.size() > 1) res.push_back(path);
        unordered_map<int,int> map;
        for(int i = startIndex;i < nums.size();i++){
            if((!path.empty() && nums[i] < path.back()) || map[nums[i]] == 1) continue;
            map[nums[i]] = 1;
            path.push_back(nums[i]);
            backtracking(nums,i + 1);
            path.pop_back();
        }
    }
    vector<vector<int>> findSubsequences(vector<int>& nums) {
        backtracking(nums,0);
        return res;
    }
};
相关推荐
王老师青少年编程5 小时前
2025年【江苏“信息与未来”编程思维】真题及题解(T2:坐标变换)
c++·题解·真题·坐标变换·编程思维·江苏·信息与未来
CS创新实验室6 小时前
算法、齿轮与硅基大脑:数值计算发展简史
人工智能·算法·数值计算
海石8 小时前
1563分的简单题,可能就简单在能被暴力AC
算法·leetcode
海石8 小时前
1400分的dp汗流浃背之【交替子数组计数】
算法·leetcode
奋发向前wcx8 小时前
P2590 树的统计 题目解析
数据结构·算法·深度优先
2023自学中8 小时前
C++ 内存追踪器
linux·c++
imbackneverdie9 小时前
AI4S不止于分子药物:以MedPeer为代表的科研基建打开产业新增量
大数据·人工智能·算法·aigc·科研·学术·ai 4s
额鹅恶饿呃10 小时前
C语言中的数据结构和变量
c语言·数据结构·算法
运行时记录11 小时前
prompt-optimizer skill
算法
万法若空11 小时前
【数据结构-哈希表】哈希表原理
数据结构·算法·散列表