leetCode---Increasing Subsequences

来源:互联网 发布:sql 2000 删除重复数据 编辑:程序博客网 时间:2024/05/16 18:47

一. 题目:Increasing Subsequences 

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]]

Note:

  1. The length of the given array will not exceed 15.
  2. The range of integer in the given array is [-100,100].
  3. The given array may contain duplicates, and two equal integers should also be considered as a special case of increasing sequence.

Subscribe to see which companies asked this question.


二. 思路分析

     题目让我们找出所有的递增子序列,首先想到迭代的解法,对于重复项的处理,最偷懒的方法是使用set,利用其自动去处重复项的机制,然后最后返回时再转回vector即可。由于是找递增序列,所以我们需要对递归函数做一些修改,首先题目中说明了递归序列数字至少两个,所以只有当当前子序列个数大于等于2时,才加入结果。然后就是要递增,如果之前的数字大于当前的数字,那么跳过这种情况,继续循环,参见代码如下:


class Solution {public:    vector<vector<int>> findSubsequences(vector<int>& nums) {        set<vector<int>> res;        vector<int> out;        helper(nums, 0, out, res);        return vector<vector<int>>(res.begin(), res.end());    }        void helper(vector<int>& nums, int start, vector<int>& out, set<vector<int>>& res) {        if (out.size() >= 2) res.insert(out);        for (int i = start; i < nums.size(); ++i) {            if (!out.empty() && out.back() > nums[i]) continue;            out.push_back(nums[i]);            helper(nums, i + 1, out, res);            out.pop_back();        }    }};

0 0
原创粉丝点击