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;
    }
};
相关推荐
郝学胜-神的一滴14 分钟前
Effective STL 条款12:对容器线程安全性的现实期望
c语言·开发语言·c++·qt·网络协议·rpc·numpy
geovindu28 分钟前
python: KNeighborsClassifier K
开发语言·后端·python·算法
让我们一起加油好吗2 小时前
【数据结构】线段树详解
数据结构·c++·算法·线段树·洛谷
路灯中转站2 小时前
数据结构C语言版(什么是数据类型)
数据结构
凌冰_2 小时前
数据结构 - 队列(五)
数据结构·算法·软件工程
sul.i3 小时前
浅析 · 分治
c++
让我们一起加油好吗4 小时前
【数据结构】ST 表
数据结构·c++·算法·动态规划·洛谷·st表
敲上瘾4 小时前
Qt 常用控件:按钮、显示输入、容器与布局等
开发语言·c++·qt·qt6.3
船神丿男人4 小时前
C++ STL 入门:用 std::string 读配置,四个容易漏掉的边界
开发语言·c++
让我们一起加油好吗4 小时前
【算法刷题】LeetCode 力扣 Hot 100 刷题记录
数据结构·c++·算法·leetcode·面试·笔试