图(深度优先搜索)491. Increasing Subsequences[Middle]03-18
来源:互联网 发布:湘阴农村淘宝 编辑:程序博客网 时间:2024/06/07 23:44
题目:
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]]
- The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.
找到所有升序的子序列。
分析:
先把所有子序列找出来,找的同时判断是否满足题意,满足的留下。
如何找子序列?
每一个序列元素有两种情况,在 或 不在某一子序列,从空集开始,选择/不选择某个元素,构成一颗二叉树,它的叶子就是全部的子序列:
所以可以递归,对每个元素进行 选择 和 不选择 的递归,终止条件是递归到了最后一个元素。是否选择这个子序列取决于这个序列是否是升序的。还有一点,这个数组有可能有重复元素,为了除去相同子集,使用stl的集合来装子集,set的特性会帮助我们去除重复集合元素。
代码:
class Solution {public: void bfs(int index, vector<int>& nums, vector<int> tmp, set<vector<int> >& result) { //终止条件,同时进入for循环判断是否是升序的,升序则加入resultif (index == nums.size()) {bool order = true;for (int i = 0; i < tmp.size(); i++) {for (int j = i + 1; j < tmp.size(); j++) {if (tmp[i] > tmp[j]) {order = false;break;}}}if(order)result.insert(tmp);}else { //选择这个元素,然后递归tmp.push_back(nums[index]);bfs(index + 1, nums, tmp, result); //不选择这个元素,然后递归tmp.pop_back();bfs(index + 1, nums, tmp, result);}} vector<vector<int>> findSubsequences(vector<int>& nums) { vector<vector<int> > ajj;set<vector<int> >result;vector<int> tmp;result.insert(tmp);bfs(0, nums, tmp, result);set<vector<int> >::iterator it = result.begin(); //把set转成题目需要的输出vectorwhile (it != result.end()) {if ((*it).size() >= 2)ajj.push_back(*it);++it;}return ajj; }};
说明:
求数组子序列有递归和非递归方法,可以参考这个链接:Grandyang的博客
0 0
- 图(深度优先搜索)491. Increasing Subsequences[Middle]03-18
- leetcode 491. Increasing Subsequences 一个典型的深度优先遍历DFS的做法
- 图(广度优先搜索)515. Find Largest Value in Each Tree Row[Middle]
- 【LeetCode】 491. Increasing Subsequences
- 491. Increasing Subsequences**
- 491. Increasing Subsequences
- LeetCode 491. Increasing Subsequences
- 491. Increasing Subsequences
- 491. Increasing Subsequences
- LeetCode 491. Increasing Subsequences
- [LeetCode]491. Increasing Subsequences
- 491. Increasing Subsequences
- [leetcode]491. Increasing Subsequences
- 【Leetcode】491. Increasing Subsequences
- [leetcode] 491. Increasing Subsequences
- 491. Increasing Subsequences
- Leetcode -- 491. Increasing Subsequences
- leetcode-491. Increasing Subsequences
- 图片处理的几种算法(毛玻璃效果,高斯模糊效果,旧时光效果,lomo效果,暖意效果)
- Git学习
- 手把手教你学Word2Vec系列三之Similarity Queries
- 让用户输入一个5位数(若不是5位数,则提示错误),判断它是不是回文数,输出判断结果。回文数:如12321是一个回文数,万位与个位相同,十位与千位相同。
- 京峰运维学习系列--2
- 图(深度优先搜索)491. Increasing Subsequences[Middle]03-18
- 非凡匠心
- Linux下的帮助命令
- 浅析Spring
- SCU
- 中美科技的霸主之争
- 谷哥的小弟学后台(41)——MyBatis的动态SQL
- Java中Public Private Protected 区别
- python快速入门精华切记02