zoukankan      html  css  js  c++  java
  • 求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 }
  • 相关阅读:
    表连接问题
    public interface Serializable?标记/标签接口
    4.21
    第十周周记
    测试
    第九周周记
    第七周周记
    fighting.
    fighting
    作业一
  • 原文地址:https://www.cnblogs.com/kirai/p/4736764.html
Copyright © 2011-2022 走看看