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;
    }
};
相关推荐
lizz318 分钟前
C++模板编程:从入门到精通
java·开发语言·c++
炽烈小老头1 小时前
【每天学习一点算法 2025/12/19】二叉树的层序遍历
数据结构·学习·算法
Queenie_Charlie1 小时前
HASH表
数据结构·c++·哈希算法
Xの哲學1 小时前
Linux grep命令:文本搜索的艺术与科学
linux·服务器·算法·架构·边缘计算
soft20015251 小时前
MySQL Buffer Pool深度解析:LRU算法的完美与缺陷
数据库·mysql·算法
superman超哥1 小时前
仓颉语言中锁的实现机制深度剖析与并发实践
c语言·开发语言·c++·python·仓颉
郝学胜-神的一滴2 小时前
OpenGL的glDrawElements函数详解
开发语言·c++·程序人生·游戏·图形渲染
WBluuue2 小时前
AtCoder Beginner Contest 436(ABCDEF)
c++·算法
fie88892 小时前
广义 S 变换(GST)地震信号时频谱
算法
辣机小司2 小时前
【软件设计师】自编思维导图和学习资料分享(中级已过)
java·c++·软考·软件设计师