leetcode 491. Increasing Subsequences所有的递增序列 + 一个典型的深度优先遍历DFS的做法

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.

首先,题意很简单,就是寻找递增子序列,使用DFS深度优先遍历去做即可,

不过需要注意的是去除重复的可能,使用set

代码如下:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

class Solution 
{
public:
    set<vector<int>> all;
    vector<vector<int>> findSubsequences(vector<int>& nums) 
    {
        dfs(nums, vector<int>(), 0);
        return vector<vector<int>>(all.begin(), all.end());
    }

    void dfs(vector<int>& a, vector<int> one, int index)
    {
        if (one.size() >= 2)
            all.insert(one);
        if (index == a.size())
            return;
        else
        {
            for (int i = index; i < a.size(); i++)
            {
                if (one.size() <= 0 || a[i] >= one.back())
                {
                    one.push_back(a[i]);
                    dfs(a, one, i + 1);
                    one.pop_back();
                }
            }
        }
    }
};

你可能感兴趣的:(leetcode,For,Java,DFS深度优先搜索,需要好好想一下的题目,leetcode,For,C++)