求n个数的组合的方法

求n个数的组合,利用二进制的0和1表示使用与不使用的两种状态可以拿来存储每一位的使用情况并且保证不会重复。代码如下:

 

 1 #include <iostream>
 2 #include <fstream>
 3 
 4 using namespace std;
 5 
 6 int main() {
 7     int arr[10];
 8     int n;
 9     int cnt = 0;
10     ofstream fs("a.txt");
11     cin >> n;
12     for(int i = 0; i < n; i++) {
13         cin >> arr[i];
14     }
15     int ss = 1 << n;    //example: n = 4 now ss = (10000)2
16     for(int i = 1; i < ss; i++) {    // i(max) = 1111, means select all numbers of arr.
17         for(int j = 0; j < n; j++) {
18             if(i & (1 << j)) {
19                 cout << arr[j] << " ";
20                 cnt++;
21             }
22         }
23         cout << endl;
24     }
25     cout << cnt << endl;
26     return 0;
27 }

 

posted @ 2015-08-17 15:39  Kirai  阅读(503)  评论(0编辑  收藏  举报