C++ 子集 II


假設我們有一組數字;我們必須生成該集合的所有可能的子集。這也被稱為冪集。我們必須記住元素可能是重複的。因此,如果集合類似於 [1,2,2],則冪集將為 [[], [1], [2], [1,2], [2,2], [1,2,2]]

讓我們看看步驟:

  • 定義一個數組 res 和另一個名為 x 的集合
  • 我們將使用遞迴方法解決這個問題。因此,如果遞迴方法名稱稱為 solve(),並且它接受索引、一個臨時陣列和數字陣列 (nums)
  • solve() 函式的工作方式如下:
  • 如果索引 = v 的大小,則
    • 如果 temp 不存在於 x 中,則將 temp 插入 res 並將 temp 插入 x
    • 返回
  • 呼叫 solve(index + 1, temp, v)
  • 將 v[index] 插入 temp
  • 呼叫 solve(index + 1, temp, v)
  • 從 temp 中刪除最後一個元素
  • 主函式如下:
  • 清除 res 和 x,並對給定陣列進行排序,定義一個數組 temp
  • 呼叫 solve(0, temp, array)
  • 對 res 陣列進行排序並返回 res

讓我們看看下面的實現以更好地理解:

示例

線上演示

#include <bits/stdc++.h>
using namespace std;
void print_vector(vector<vector<int> > 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;
   set < vector <int> > x;
   static bool cmp(vector <int> a, vector <int> b){
      return a < b;
   }
   void solve(int idx, vector <int> temp, vector <int> &v){
      if(idx == v.size()){
         if(x.find(temp) == x.end()){
            res.push_back(temp);
            x.insert(temp);
         }
         return;
      }
      solve(idx+1, temp, v);
      temp.push_back(v[idx]);
      solve(idx+1, temp, v);
      temp.pop_back();
   }
   vector<vector<int> > subsetsWithDup(vector<int> &a) {
      res.clear();
      x.clear();
      sort(a.begin(), a.end());
      vector <int> temp;
      solve(0, temp, a);
      sort(res.begin(), res.end(), cmp);
      return res;
   }
};
main(){
   Solution ob;
   vector<int> v = {1,2,2};
   print_vector(ob.subsetsWithDup(v));
}

輸入

[1,2,2]

輸出

[[],[1, ],[1, 2, ],[1, 2, 2, ],[2, ],[2, 2, ],]

更新於:2020年5月4日

328 次瀏覽

開啟您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.