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;
    }
};
相关推荐
芒果量化6 分钟前
Optuna - 自动调参利器&python实例
开发语言·python·算法·机器学习
麦麦大数据9 分钟前
D025 摩托车推荐价格预测可视化系统|推荐算法|机器学习|预测算法|用户画像与数据分析
mysql·算法·机器学习·django·vue·推荐算法·价格预测
阿林学习计算机18 分钟前
红黑树的实现
数据结构
CoovallyAIHub35 分钟前
IDEA研究院发布Rex-Omni:3B参数MLLM重塑目标检测,零样本性能超越DINO
深度学习·算法·计算机视觉
豐儀麟阁贵1 小时前
4.4数组的基本操作
java·开发语言·数据结构·算法
我狸才不是赔钱货1 小时前
AI大模型“战国策”:主流LLM平台简单介绍
c++·人工智能·程序人生·github·llama
无限进步_1 小时前
【C语言】在矩阵中高效查找数字的算法解析
c语言·开发语言·数据结构·c++·其他·算法·矩阵
小白要加油努力1 小时前
滑动窗口的典例以及思路阐述
算法
Yupureki1 小时前
从零开始的C++学习生活 11:二叉搜索树全面解析
c语言·数据结构·c++·学习·visual studio
草莓工作室1 小时前
数据结构2:线性表1-线性表类型及其特点
c语言·数据结构