C++ 中的遞增子序列


假設我們有一個整數陣列,我們的任務是找到給定陣列的所有不同的可能的遞增子序列,並且遞增子序列的長度至少為 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 用於儲存所有結果
  • 建立一個名為 solve 的方法。這將接收 nums 陣列、start 和 temp 陣列
  • 如果 temp 的大小 > 1,則將 temp 插入 res
  • 建立一個名為 visited 的集合
  • 對於 i 在 start 到 nums 大小範圍內
    • x := nums[i]
    • 如果 x 在 visited 集合中,則跳過迴圈的下一部分
    • 將 x 插入 visited 集合
    • 如果 temp 為空或 temp 的最後一個元素 <= x,則
      • 將 x 插入 temp
      • 呼叫 solve(nums, i + 1, temp)
      • 從 temp 的末尾刪除一個元素
  • 從主方法中,呼叫 solve(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, ],]

更新於: 2020年5月2日

178 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.