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 <= numsi <= 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;
    }
};
相关推荐
小poop几秒前
高级排序算法与性能对比——归并、非比较排序及总结
数据结构·算法·排序算法
aqiu111111几秒前
CodeTop按顺序刷题0003:LeetCode 206. 反转链表(迭代法图文详解与动态演示)
算法·leetcode·链表
纪念 22923 分钟前
C++ vector(一)
开发语言·c++
果霸大叔27 分钟前
AI网关第8篇:AI 代理与负载均衡--多模型实例如何调度?
人工智能·算法·自然语言处理·负载均衡·ai-native
用户849137175471631 分钟前
Redis 跳表用了"随机"的魔法,实现了比平衡树更快的查找!
数据结构·redis
不会就选b32 分钟前
算法日常・每日刷题--<动态规划>29
数据结构·算法·leetcode
垆边人似月.41 分钟前
最少的元素个数使和为 target
数据结构·c++·算法
炽橙超真云42 分钟前
2D 工程图纸如何自动转成可编辑 3D 模型?拆解读图与建体两条技术路径(DXF/DWG/PDF 到 STEP)
算法·3d·工业智能·工业ai
Zip-List1 小时前
工作小记-pytorch的算子优化: 转gpu核函数 python调c
c语言·c++·pytorch·python·cuda
夕除1 小时前
redis--dict rehash
算法·哈希算法