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;
    }
};
相关推荐
Miki Makimura1 分钟前
C++ 聊天室项目:Linux 环境搭建与问题总结
linux·开发语言·c++
CappuccinoRose3 分钟前
排序算法和查找算法 - 软考备战(十五)
数据结构·python·算法·排序算法·查找算法
旖-旎5 分钟前
分治(交易逆序对的总数)(6)
c++·算法·leetcode·排序算法·归并排序
北顾笙9805 分钟前
day14-数据结构力扣
数据结构·算法·leetcode
郝学胜-神的一滴6 分钟前
[简化版 GAMES 101] 计算机图形学 03:线性代数下
开发语言·c++·线性代数·图形渲染
Ln5x9qZC213 分钟前
尾递归与Continuation
算法
一路向北he14 分钟前
esp32库依赖
c语言·c++·算法
老四啊laosi14 分钟前
[双指针] 6. 查找总价为目标值的两个商品
算法·力扣·总价为目标值得两商品
Howrun77724 分钟前
C++ 项目测试全指南:从 0 基础到落地实操
开发语言·c++·log4j
YYYing.25 分钟前
【Linux/C++网络篇(二) 】TCP并发服务器演进史:从多进程到Epoll的进化指南
linux·服务器·网络·c++·tcp/ip