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;
    }
};
相关推荐
2301_764441333 分钟前
新能源汽车电磁辐射高级预测
python·算法·数学建模·汽车
Keep_Trying_Go9 分钟前
论文Leveraging Unlabeled Data for Crowd Counting by Learning to Rank算法详解
人工智能·pytorch·深度学习·算法·人群计数
fpcc12 分钟前
跟我学C++中级篇——重载问题分析之函数模板重载的问题
c++
仟濹27 分钟前
【C/C++】经典高精度算法 5道题 加减乘除「复习」
c语言·c++·算法
顾安r43 分钟前
11.21 脚本 网页优化
linux·前端·javascript·算法·html
kk”1 小时前
C++ map
开发语言·c++
共享家95271 小时前
特殊类的设计
开发语言·c++
WolfGang0073211 小时前
代码随想录算法训练营Day27 | 56.合并区间、738.单调递增的数字、968.监控二叉树
算法
xiaoye-duck1 小时前
数据结构之排序-选择排序&交换排序
数据结构·排序算法
小此方2 小时前
笔记:树。
数据结构·笔记