यह C++ प्रोग्राम दिए गए कैरेक्टर ऐरे (जैसे a, b, c, d, e) के सभी संभावित कॉम्बिनेशन (संयोजन) उत्पन्न करता है। यह रिकर्सिव बैकट्रैकिंग दृष्टिकोण का उपयोग करता है।
एल्गोरिदम
शुरुआत
1. तत्वों की संख्या और तत्वों को इनपुट लें।
2. फंक्शन Combi(char a[], int reqLen, int start, int currLen, bool check[], int len):
- यदि currLen > reqLen तो लौटें
- अन्यथा यदि currLen == reqLen तो नई जनरेटेड सीक्वेंस प्रिंट करें
- यदि start == len तो लौटें (कोई और तत्व नहीं बचा)
- प्रत्येक इंडेक्स के लिए दो विकल्प:
* check[start] = true सेट करें और Combi() को currLen+1 और start+1 के साथ रिकर्सिवली कॉल करें
* check[start] = false सेट करें और Combi() को केवल start+1 के साथ रिकर्सिवली कॉल करें
समाप्ति
उदाहरण कोड
#include <iostream>
using namespace std;
void Combi(char a[], int reqLen, int start, int currLen, bool check[], int len) {
if (currLen > reqLen) return;
else if (currLen == reqLen) {
cout << "\t";
for (int i = 0; i < len; i++) {
if (check[i] == true)
cout << a[i] << " ";
}
cout << "\n";
return;
}
if (start == len) return;
check[start] = true;
Combi(a, reqLen, start + 1, currLen + 1, check, len);
check[start] = false;
Combi(a, reqLen, start + 1, currLen, check, len);
}
int main() {
int n;
cout << "Enter the number of elements in array: ";
cin >> n;
char a[n];
bool check[n];
cout << "\n";
for (int i = 0; i < n; i++) {
cout << "Enter " << i+1 << " element: ";
cin >> a[i];
check[i] = false;
}
for (int i = 1; i <= n; i++) {
cout << "\nThe all possible combinations of length " << i << " for the given array set:\n";
Combi(a, i, 0, 0, check, n);
}
return 0;
}
आउटपुट
Enter the number of elements in array: 5 Enter 1 element: a Enter 2 element: b Enter 3 element: c Enter 4 element: d Enter 5 element: e The all possible combinations of length 1 for the given array set: a b c d e The all possible combinations of length 2 for the given array set: a b a c a d a e b c b d b e c d c e d e The all possible combinations of length 3 for the given array set: a b c a b d a b e a c d a c e a d e b c d b c e b d e c d e The all possible combinations of length 4 for the given array set: a b c d a b c e a b d e a c d e b c d e The all possible combinations of length 5 for the given array set: a b c d e
कुल कॉम्बिनेशन: n तत्वों के लिए, कुल 2^n - 1 नॉन-खाली सबसेट होते हैं। यह प्रोग्राम उन्हें लंबाई के अनुसार व्यवस्थित करके दिखाता है।