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;
    }
};
相关推荐
煤球王子9 分钟前
学而时习之:C++中的结构体
c++
码银33 分钟前
【数据结构】单链表核心知识点梳理
数据结构
一只老丸34 分钟前
HOT100题打卡第36天——二分查找
数据结构·算法
潼心1412o1 小时前
数据结构(长期更新)第7讲:栈
数据结构
陌路201 小时前
S19 哈希--6种哈希构造方法
算法·哈希算法
散峰而望1 小时前
C++入门(算法) - 习题
开发语言·c++·算法·github
这张生成的图像能检测吗1 小时前
(论文速读)Regor - 渐进式对应点再生实现鲁棒3D配准
人工智能·算法·计算机视觉·配准·3d点云
Fency咖啡1 小时前
redis进阶 - 底层数据结构
数据结构·数据库·redis
blog_wanghao1 小时前
PDF文件内容出现重叠现象解析
c++·pdf
yong99902 小时前
C++实现LBM模拟Couette流
开发语言·c++