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;
    }
};
相关推荐
追随者永远是胜利者1 天前
(LeetCode-Hot100)64. 最小路径和
java·算法·leetcode·职场和发展·go
汉克老师1 天前
GESP2024年6月认证C++二级( 第三部分编程题(1) 平方之和)
c++·算法·预处理·完全平方数·循环结构·gesp二级·gesp2级
StandbyTime1 天前
《算法笔记》练习记录-2.5-问题 C: 习题6-6 杨辉三角
c++·算法笔记
云深处@1 天前
【题】每日一题
算法
MR_Promethus1 天前
【C++11】condition_variable 条件变量
c++·条件变量·并发编程
智者知已应修善业1 天前
【排列顺序判断是否一次交换能得到升序】2025-1-28
c语言·c++·经验分享·笔记·算法
fpcc1 天前
并行编程实战——CUDA编程的内存建议
c++·cuda
yzs871 天前
OLAP数据库HashJoin性能优化揭秘
数据库·算法·性能优化·哈希算法
好家伙VCC1 天前
**发散创新:编译器优化实战——从LLVM IR到性能飞跃的奇妙旅程**
java·开发语言·python·算法
季明洵1 天前
数据在内存中的存储
数据结构·算法·c