C++ 中按字典排序的冪集


在此問題中,我們給定字串 str。我們的任務是按字典序列印此字串元素的冪集。

冪集 - 冪集是集合的所有子集的集合。表示為 P(S),其中 s 是集合。

示例 -

S = {1, 2, 3} ;
p(S) = {{}, {1}, {1, 2}, {1, 3}, {2}, {2, 3}, {3}, {1,2,3}}

在此問題中,我們將字串視為一個集合。因此,它的字元將成為集合的元素。

讓我們舉一個例子來理解這個問題

輸入 - str = “xyz”

輸出 - x xy xyz xz y yz z

為了解決這個問題,我們必須對陣列進行排序,以便獲得字典序。然後我們將固定字串中的一個元素並遞迴呼叫剩下的元素,這些元素將生成所有子字串。然後捨棄第一個固定元素以獲得下一個排列。

示例

展示我們解決方案實現的程式,

 即時演示

#include <bits/stdc++.h>
using namespace std;
void printAllSubsets(string str, int n, int index = -1, string subset = "") {
   if (index == n)
      return;
   cout<<subset<<"\n";
   for (int i = index + 1; i < n; i++) {
      subset+= str[i];
      printAllSubsets(str, n, i, subset);
      subset = subset.erase(subset.size() - 1);
   }
   return;
}
void GeneratePowerSet(string str) {
   sort(str.begin(), str.end());
   printAllSubsets(str, str.size());
}
int main() {
   string str = "xyz";
   cout<<"Power Set of the string '"<<str<<"' is :\n";
   GeneratePowerSet(str);
   return 0;
}

輸出

Power Set of the string 'xyz' is:
x xy xyz xz y yz z

更新於: 17-4-2020

675 瀏覽量

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.