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 <= nums[i] <= 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 小时前
C++ std::list 深度解析:迭代器、splice 核心接口与排序效率全解
开发语言·c++
笨笨饿14 小时前
#65_反激电源
stm32·单片机·嵌入式硬件·算法·硬件工程·个人开发
艾莉丝努力练剑14 小时前
【Linux网络】计算机网络入门:从背景到协议,理解网络通信基础
linux·运维·服务器·c++·学习·计算机网络
艾莉丝努力练剑14 小时前
【Linux线程】Linux系统多线程(十):线程安全和重入、死锁相关话题
java·linux·运维·服务器·c++·学习·安全
wengqidaifeng14 小时前
数据结构:排序(下)---进阶排序算法详解
数据结构·算法·排序算法
MicroTech202514 小时前
突破单机量子计算限制:MLGO微算法科技的新型分布式量子算法模拟平台实现高效验证
科技·算法·量子计算
没有天赋那就反复14 小时前
C++里面引用参数和实参的区别
开发语言·c++·算法
ximu_polaris14 小时前
设计模式(C++)-创造型模式-建造者模式
c++·设计模式·建造者模式
wengqidaifeng14 小时前
数据结构:排序(上)---基础排序算法详解
数据结构·算法·排序算法
TIEM_6914 小时前
C++string接口(下)|修改器、字符串操作、成员常量、非成员函数重载
开发语言·c++