Increasing Subsequences in C++

C++Server Side ProgrammingProgramming

Suppose we have an integer array, our 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. So if the array is like [4,6,7,7], then the output will be like − [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]].

To solve this, we will follow these steps −

  • Define an array, called res to store all results
  • Make a method called solve. This will take nums array, start and temp array
  • if the size of temp > 1, then insert temp into res
  • make a set called visited
  • for i in range start to size of nums
    • x := nums[i]
    • if x in visited set, then skip the next part of the loop
    • insert x into visited set
    • if temp is empty or last element of temp <= x, then
      • insert x into temp
      • call solve(nums, i + 1, temp)
      • delete one element from end of temp
  • From the main method, call solve(nums, 0, temp)
  • return res

Let us see the following implementation to get better understanding −

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<auto> > v){
   cout << "[";
   for(int i = 0; i<v.size(); i++){
      cout << "[";
      for(int j = 0; j <v[i].size(); j++){
         cout << v[i][j] << ", ";
      }
      cout << "],";
   }
   cout << "]"<<endl;
}
class Solution {
   public:
   vector < vector <int> > res;
   void solve( vector <int>& nums, int start, vector <int> temp){
      if(temp.size() > 1){
         res.push_back(temp);
      }
      set <int> visited;
      for(int i = start; i < nums.size(); i++){
         int x = nums[i];
         if(visited.count(x))continue;
         visited.insert(x);
         if(temp.empty() || temp[temp.size() - 1] <= x){
            temp.push_back(x);
            solve(nums, i + 1, temp);
            temp.pop_back();
         }
      }
   }
   vector<vector<int>> findSubsequences(vector<int>& nums) {
      res.clear();
      vector <int> temp;
      solve(nums, 0, temp);
      return res;
   }
};
main(){
   vector<int> v = {5,6,7,8};
   Solution ob;
   print_vector(ob.findSubsequences(v));
}

Input

[4,6,7,8]

Output

[[5, 6, ],[5, 6, 7, ],[5, 6, 7, 8, ],[5, 6, 8, ],[5, 7, ],[5, 7, 8, ],[5, 8, ],[6, 7, ],[6, 7, 8, ],[6, 8, ],[7, 8, ],]
raja
Published on 02-May-2020 13:02:21
Advertisements