Leetcode -- 491. Increasing Subsequences

来源:互联网 发布:别斯兰人质事件知乎 编辑:程序博客网 时间:2024/06/02 13:11

题目:

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:
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.


思路:
这是一个典型的深搜问题,遍历到最后的结点时,回溯。


C++ Codes:

class Solution{public:    vector<vector<int>> findSubsequences(vector<int>& nums) {        vector<vector<int>> res;        vector<int> tmp;        tmp.clear();        dfs(res,nums,tmp,0);        return res;    }    void dfs(vector<vector<int>>& res, vector<int>& nums, vector<int>& tmp, int index)    {        if(tmp.size()>=2)            res.push_back(tmp);        unordered_set<int> s; //基于hash的无序集合,访问速度更快        for(int i=index;i<nums.size();i++)        {            if((tmp.empty()||tmp.back()<=nums[i])&&s.find(nums[i]) == s.end()) //nums[i]不在s中,返回s.end()            {                tmp.push_back(nums[i]);                dfs(res,nums,tmp,i+1);                tmp.pop_back(); //回溯                s.insert(nums[i]); //将nums[i]加入到s中            }        }    }};
0 0
原创粉丝点击