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;
    }
};
相关推荐
xieliyu.1 分钟前
Java手搓数据结构:从零模拟实现无头双向非循环链表
java·数据结构·链表
爱学习的张大5 分钟前
具身智能论文精读(五):OpenVLA
人工智能·算法
水云桐程序员16 分钟前
C++的主要应用场景
c++·学习方法
刘大猫.1 小时前
宝马发布全新AI智能座舱助手 能理解用户复杂出行需求
人工智能·算法·机器学习·ai·大模型·算力·ai智能座舱助手
如何原谅奋力过但无声1 小时前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
leoufung1 小时前
LeetCode 42:接雨水 —— 从“矩形法”到双指针的完整思考过程
java·算法·leetcode
叼烟扛炮1 小时前
C++第一讲:C++ 入门基础
开发语言·c++·函数重载·引用·内联函数·nullptr
zh_xuan2 小时前
使用libcurl调用http接口
c++·github·libcurl
zh路西法2 小时前
【RDKX5多摄像头模型推理】USB带宽限制与ROS2话题零拷贝转发
linux·c++·python·深度学习
千寻girling2 小时前
五一劳动节快乐 [特殊字符][特殊字符][特殊字符]
java·c++·git·python·学习·github·php