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;
    }
};
相关推荐
点云SLAM1 小时前
二叉树算法详解和C++代码示例
数据结构·c++·算法·红黑树·二叉树算法
m0_535064608 小时前
C++模版编程:类模版与继承
java·jvm·c++
今天背单词了吗9808 小时前
算法学习笔记:19.牛顿迭代法——从原理到实战,涵盖 LeetCode 与考研 408 例题
笔记·学习·算法·牛顿迭代法
没书读了8 小时前
考研复习-数据结构-第六章-图
数据结构
jdlxx_dongfangxing9 小时前
进制转换算法详解及应用
算法
Tanecious.9 小时前
C++--红黑树封装实现set和map
网络·c++
why技术10 小时前
也是出息了,业务代码里面也用上算法了。
java·后端·算法
future141211 小时前
C#进阶学习日记
数据结构·学习
2501_9228955811 小时前
字符函数和字符串函数(下)- 暴力匹配算法
算法
IT信息技术学习圈11 小时前
算法核心知识复习:排序算法对比 + 递归与递推深度解析(根据GESP四级题目总结)
算法·排序算法