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;
    }
};
相关推荐
long_run18 分钟前
C++之auto 关键字
c++
卡洛斯(编程版38 分钟前
(1) 哈希表全思路-20天刷完Leetcode Hot 100计划
python·算法·leetcode
疯狂的代M夫39 分钟前
C++对象的内存布局
开发语言·c++
NAGNIP2 小时前
DeepSeekMoE 架构解析
算法
重启的码农2 小时前
llama.cpp 分布式推理介绍(4) RPC 服务器 (rpc_server)
c++·人工智能·神经网络
重启的码农2 小时前
llama.cpp 分布式推理介绍(3) 远程过程调用后端 (RPC Backend)
c++·人工智能·神经网络
不喜欢学数学er2 小时前
算法第五十二天:图论part03(第十一章)
算法·深度优先·图论
养成系小王2 小时前
四大常用排序算法
数据结构·算法·排序算法
NAGNIP2 小时前
一文搞懂DeepSeek LLM
算法
敲上瘾2 小时前
Linux I/O 多路复用实战:Select/Poll 编程指南
linux·服务器·c语言·c++·select·tcp·poll