Problem
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.
Solution: DFS
Time complexity: O(2^n)
Space complexity: O(n)
C++
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
// Author: Huahua // Running time: 140 ms (<99.88%) class Solution { public: vector<vector<int>> findSubsequences(vector<int>& nums) { vector<vector<int>> ans; vector<int> cur; dfs(nums, 0, cur, ans); return ans; } private: void dfs(const vector<int>& nums, int s, vector<int>& cur, vector<vector<int>>& ans) { unordered_set<int> seen; for (int i = s; i < nums.size(); ++i) { if (!cur.empty() && nums[i] < cur.back()) continue; // each number can be used only once at the same depth. if (seen.count(nums[i])) continue; seen.insert(nums[i]); cur.push_back(nums[i]); if (cur.size() > 1) ans.push_back(cur); dfs(nums, i + 1, cur, ans); cur.pop_back(); } } }; |