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;
    }
};
相关推荐
v_for_van4 分钟前
力扣刷题记录1(无算法背景,纯C语言)
算法·leetcode·职场和发展
从此不归路7 分钟前
Qt5 进阶【10】应用架构与插件化设计实战:从「单体窗口」走向「可扩展框架」
开发语言·c++·qt·架构
瓦特what?7 分钟前
C++编程防坑指南(小说版)
android·c++·kotlin
sjjhd6529 分钟前
C++模拟器开发实践
开发语言·c++·算法
踩坑记录9 分钟前
leetcode hot100 25. K 个一组翻转链表 hard
leetcode·链表
七夜zippoe10 分钟前
大模型低成本高性能演进 从GPT到DeepSeek的技术实战手记
人工智能·gpt·算法·架构·deepseek
二年级程序员11 分钟前
qsort函数的使用与模拟实现
c语言·数据结构·算法·排序算法
Queenie_Charlie13 分钟前
素数(线性筛法)
c++·线性筛法·质数·简单数论
莹莹学编程—成长记15 分钟前
TCP/IP五层模型+网络传输基本流程
网络·c++
ajole18 分钟前
C++学习笔记——C++11
数据结构·c++·笔记·学习·算法·stl