图(深度优先搜索)491. Increasing Subsequences[Middle]03-18

题目:

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循环判断是否是升序的,升序则加入result
	if (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转成题目需要的输出vector
	while (it != result.end()) {
		if ((*it).size() >= 2)
			ajj.push_back(*it);

		++it;
	}

	return ajj;       
    }
};



说明:

求数组子序列有递归和非递归方法,可以参考这个链接:Grandyang的博客


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值