1. Recursive Subsequence Generation
Intuition
Generate all 2n subsequences, filter for strictly increasing order, find max length, and count them.
Algorithm
- Generate all subsets of indices.
- Verify if values are strictly increasing.
- Record max length and maintain a frequency map.
- Return the count corresponding to the maximum length.
#include <iostream>#include <vector>#include <algorithm> using namespace std; class Solution { void dfs(int idx, vector<int>& current, const vector<int>& nums, int& maxLen, int& count) { if (idx == nums.size()) { if (current.size() > maxLen) { maxLen = current.size(); count = 1; } else if (current.size() == maxLen && maxLen > 0) { count++; } return; } // Exclude dfs(idx + 1, current, nums, maxLen, count); // Include if (current.empty() || nums[idx] > current.back()) { current.push_back(nums[idx]); dfs(idx + 1, current, nums, maxLen, count); current.pop_back(); } }public: int findNumberOfLIS(vector<int>& nums) { if (nums.empty()) return 0; int maxLen = 0, count = 0; vector<int> current; dfs(0, current, nums, maxLen, count); return count; }}; int main() { Solution sol; vector<int> nums = {1, 3, 5, 4, 7}; cout << "Number of LIS: " << sol.findNumberOfLIS(nums) << endl; return 0;}Time & Space Complexity
- Time complexity:
O(2^n * n) - Space complexity:
O(n)