/ Published in: C++
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/* * combination.cpp * * Created on: 2011/3/25 * Author: dirk */ // for convenience, indexing in this alg. starts from 1 #include <iostream> using namespace std; #define MAX 512 inline int advance_and_relax(int digits[], int m, int n) { if(n == 1) return 0; // no way to advance for(int i = n - 1; i >= 1; --i) { if(++digits[i] <= (m - n + i)) { // digits[i] is able to advance for(int cur_index = i+1, cur_value = digits[i]+1; cur_index <= n; ++cur_index) { // we relax all digits behind digits[i] digits[cur_index] = cur_value++; } return 1; } } return 0; } inline void C(int x[], int m, int n) { int digits[MAX+1]; // our indexing starts from 1 for(int i = 0; i < n + 1; ++i) digits[i] = i; // initialization int finish = 0; while(finish == 0) { for(int i = 1; i <= n; ++i) cout << x[digits[i]] << ' '; cout << '\n'; if(++digits[n] > m) { if(advance_and_relax(digits, m, n) == 1) finish = 0; else finish = 1; } } } int main() { int m, n; int x[MAX+1]; cout << "M = ? "; cin >> m; cout << "N = ? "; cin >> n; cout << "輸入 M 個數å—: "; for(int i = 1; i <= m; ++i) cin >> x[i]; if(m < n || m <=0 || n <= 0 || m > 512) { cout << "è¼¸å…¥æ ¼å¼ä¸æ£ç¢º, 界線æ¢ä»¶æ˜¯ M > N 且 M, N > 0\n" << "記憶體é™åˆ¶æ˜¯ M å¿…é ˆå°æ–¼ç‰æ–¼ 512\n" << "真的 M å¤ªå¤§ä¹Ÿæœƒç®—å¾ˆä¹…æ€•ä½ æ²’è€å¿ƒXD\n"; return -1; } C(x, m, n); }