fork(1) download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. int main(){
  5. int array [] = { 2,10,4,5,7,1,3,9,6,8,11,12};
  6. int length=10;
  7. int requiredSum=16;
  8. int sum=0;
  9. // 循环子集
  10. for (unsigned int i=1; i<(1<<length); ++i,sum=0) {
  11. for (unsigned int k=0; k<32; ++k)
  12. if ((i&(1<<k)))//检查是否含有第K个元素
  13. sum += array[k];
  14. if (sum==requiredSum){
  15. for (unsigned int k=0; k<32; ++k )
  16. if ((i&(1<<k)))
  17. cout << array[k] << ' ';
  18. cout << endl;
  19. }
  20. }
  21. }
Success #stdin #stdout 0.02s 2724KB
stdin
Standard input is empty
stdout
2 10 4 
4 5 7 
10 5 1 
2 4 7 3 
2 10 1 3 
5 7 1 3 
2 5 9 
7 9 
2 4 1 9 
4 3 9 
10 6 
4 5 1 6 
2 7 1 6 
2 5 3 6 
7 3 6 
2 4 1 3 6 
1 9 6 
2 5 1 8 
7 1 8 
5 3 8 
4 1 3 8 
2 6 8