C++ 中的递增子序列

c++server side programmingprogramming更新于 2025/6/26 23:07:17

假设我们有一个整数数组,我们的任务是找出给定数组中所有可能的递增子序列,递增子序列的长度至少为 2。因此,如果数组长度为 [4,6,7,7],则输出将类似于 − [[4, 6], [4, 7], [4, 6, 7], [4, 6, 7, 7], [6, 7], [6, 7, 7], [7,7], [4,7,7]]。

为了解决这个问题,我们将遵循以下步骤 −

  • 定义一个名为 res 的数组来存储所有结果
  • 创建一个名为 resolve 的方法。这将需要 nums 数组、start 和 temp 数组
  • 如果 temp 的大小 > 1,然后将 temp 插入 res
  • 创建一个名为 visitor 的集合
  • for i in range start to size of nums
    • x := nums[i]
    • 如果 x 在 vi​​sitor 集合中,则跳过循环的下一部分
    • 将 x 插入 visitor 集合
    • 如果 temp 为空或 temp 的最后一个元素 <= x,则
      • 将 x 插入 temp
      • 调用 resolve(nums, i + 1, temp)
      • 从 temp 末尾删除一个元素
  • 在主方法中,调用 resolve(nums, 0, temp)
  • 返回 res

让我们看看下面的实现以便更好地理解 −

示例

#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));
}

输入

[4,6,7,8]

输出

[[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, ],]

相关文章