本文主要是介绍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进行去重
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;}
};
这篇关于LeetCode491. Non-decreasing Subsequences的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!