图(深度优先搜索)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]]


  1. 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
原创粉丝点击