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

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.

class Solution {
public:
    set<vector<int>> st;//便于去重
    vector<vector<int>> findSubsequences(vector<int>& nums) {
    vector<int> cur;//当前子序列;
    dfs(cur,nums,0);
    vector<vector<int>> res(st.begin(),st.end());
    return res;
    }
    void dfs(vector<int>& cur,vector<int>& nums,int curIndex)
    {
        if(curIndex ==nums.size())//超过边界
        {
            if(cur.size()>1)
            st.insert(cur);
            return;
        }
        if(cur.size()==0 ||nums[curIndex] >=cur.back())
        {
            cur.push_back(nums[curIndex]);
            dfs(cur,nums,curIndex+1);
            cur.pop_back();
        }

        dfs(cur,nums,curIndex+1);//这行递归相当于遍历了每一个数字开头的序列
        //相当于常规的深度搜索外,套了一层循环
    }
};

注意:深度搜索两种不同的写法,有的再外侧套了一层循环,有的直接返回后接着递归。

posted @ 2020-08-25 16:18  zmachine  阅读(144)  评论(0编辑  收藏  举报