LeetCode C++ 491. Increasing Subsequences【DFS】中等
发布日期:2021-07-01 02:50:23
浏览次数:3
分类:技术文章
本文共 1407 字,大约阅读时间需要 4 分钟。
Given an integer array, your task is to find all the different possible increasing subsequences of the given array, and the length of an increasing subsequence should be at least 2
.
Example:
Input: [4, 6, 7, 7]Output: [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]
Constraints:
- The length of the given array will not exceed
15
. - The range of integer in the given array is
[-100,100]
. - The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.
题意:找到所有该数组的递增子序列,递增子序列的长度至少是 2
。
思路1:用 set
去重,然后DFS+回溯解决。需要注意的是:递增子序列必须是不同的;相等的数字也是递增的一种情况;只要子序列递增并且大小 >= 2
,就可以插入到 set
中。整个代码如下:
class Solution { public: set> res; vector > findSubsequences(vector & nums) { vector tmp; dfs(nums, 0, tmp); return vector >(res.begin(),res.end()); } void dfs(vector & nums, int i, vector &tmp){ if (tmp.size() >= 2) { res.insert(tmp); } for(int j = i; j < nums.size(); ++j){ if (!tmp.empty() && tmp.back() > nums[j]) continue; tmp.push_back(nums[j]); dfs(nums, j + 1, tmp); tmp.pop_back(); } }};
效率较低:
执行用时:228 ms, 在所有 C++ 提交中击败了34.51% 的用户内存消耗:22.1 MB, 在所有 C++ 提交中击败了67.70% 的用户
还有其他解法,日后再更新。
转载地址:https://memcpy0.blog.csdn.net/article/details/108251145 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
很好
[***.229.124.182]2024年04月29日 00时19分47秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
剑指offer31:栈的压入、弹出序列
2019-05-03
JVM类加载运行内存过程
2019-05-03
在光标处插入指定文本(支持文本域和文本框)
2019-05-03
js实现excel导出
2019-05-03
Extjs4 中在指定光标处插入值
2019-05-03
windows7家庭普通版升级为旗舰版
2019-05-03
windows7+iis7+php的配置
2019-05-03
UML中的协作图
2019-05-03
Extjs4中combo的联动选择
2019-05-03
Extjs4中Ext.ajax.request
2019-05-03
UML中的活动图
2019-05-03
UML中的对象图
2019-05-03
UML中的顺序图
2019-05-03
UML中的状态图
2019-05-03
UML模型
2019-05-03
UML中的构件图
2019-05-03
UML中的部署图
2019-05-03
Extjs4 中的gird
2019-05-03
js中的Call与apply方法
2019-05-03
Ehcache中配置详解
2019-05-03