นี่คือโปรแกรม C++ สำหรับสร้างทุกชุดการจัดหมู่ (Combinations) ที่เป็นไปได้ของรายการตัวเลขที่กำหนด
อัลกอริทึม
เริ่มต้น รับจำนวนองค์ประกอบและองค์ประกอบต่างๆ เป็นอินพุต ฟังก์ชัน Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) : ถ้า currLen > reqLen แล้ว คืนค่า มิฉะนั้น ถ้า currLen = reqLen แล้ว พิมพ์ลำดับที่สร้างขึ้นใหม่ ถ้า s = l แล้ว คืนค่า ไม่มีองค์ประกอบเหลือ สำหรับทุกดัชนี มี 2 ทางเลือก: ไปต่อกับ start เป็น 'true' และเรียก Combi() แบบเรียกซ้ำพร้อมเพิ่มค่า 'currLen' และ 's' หรือไปต่อกับ start เป็น 'false' และเรียก Combi() แบบเรียกซ้ำพร้อมเพิ่มค่า 's' เท่านั้น จบ
ตัวอย่างโค้ด
#include<iostream> using namespace std; void Combi(char a[], int reqLen, int s, int currLen, bool check[], int l) // พิมพ์ทุกชุดการจัดหมู่ของชุดอาร์เรย์ที่กำหนด { if(currLen > reqLen) return; else if (currLen == reqLen) { cout<<"\t"; for (int i = 0; i < l; i++) { if (check[i] == true) { cout<<a[i]<<" "; } } cout<<"\n"; return; } if (s == l) { return; } check[s] = true; Combi(a, reqLen, s + 1, currLen + 1, check, l); //เรียก Combi() แบบเรียกซ้ำพร้อมเพิ่มค่า 'currLen' และ 's' check[s] = false; Combi(a, reqLen, s + 1, currLen, check, l); // เรียก Combi() แบบเรียกซ้ำพร้อมเพิ่มค่า 's' เท่านั้น } int main() { int i,n; bool check[n]; cout<<"Enter the number of element array have: "; cin>>n; char a[n]; cout<<"\n"; for(i = 0; i < n; i++) { cout<<"Enter "<<i+1<<" element: "; cin>>a[i]; check[i] = false; } for(i = 1; i <= n; i++) { cout<<"\nThe all possible combination of length "<<i<<" for the given array set:\n"; Combi(a, i, 0, 0, check, n); } return 0; }
ผลลัพธ์
Enter the number of element array have: 4 Enter 1 element: 4 Enter 2 element: 3 Enter 3 element: 2 Enter 4 element: 1 The all possible combination of length 1 for the given array set: 4 3 2 1 The all possible combination of length 2 for the given array set: 4 3 4 2 4 1 3 2 3 1 2 1 The all possible combination of length 3 for the given array set: 4 3 2 4 3 1 4 2 1 3 2 1 The all possible combination of length 4 for the given array set: 4 3 2 1