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;
    }
};
相关推荐
美式请加冰2 分钟前
位运算符的介绍和使用
数据结构·算法
tankeven4 分钟前
HJ127 小红的双生串
c++·算法
Fcy6486 分钟前
与链表有关的算法题
数据结构·算法·链表
KerwinChou_CN8 分钟前
LangGraph 快速入门
服务器·网络·算法
雨落在了我的手上11 分钟前
C语言之数据结构初见篇(2):顺序表之通讯录的实现
数据结构
安之若素.re26 分钟前
918. 环形子数组的最大和
算法
阿阿阿阿里郎29 分钟前
ROS2快速入门--C++基础
开发语言·c++·算法
free-elcmacom31 分钟前
C++<x>new和delete
开发语言·c++·算法
lxh011334 分钟前
计算右侧小于当前元素的个数 题解
javascript·数据结构·算法
ouliten36 分钟前
[CUTLASS笔记2]host端工具类
c++·笔记·cuda·cutlass