1. 程式人生 > 其它 >集合遍歷(子集遍歷)--二進位制

集合遍歷(子集遍歷)--二進位制

集合的概念

寫法一:

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int u;
 4 int n, a[10];
 5 int main()
 6 {
 7     cin>>n;
 8     for(int i=0; i<n; i++)
 9         cin>>a[i];
10         
11     cout<<"原集合為:{";
12     for(int i=0; i<n; i++)
13         cout<<a[i]<<"
,"; 14 cout<<"}"<<endl; 15 16 //將集合轉二進位制 17 for(int i=0; i<4; i++){ 18 u+=(1<<a[i]); 19 } 20 21 cout<<"該集合的非空子集為"<<endl; 22 // 遍歷 u 的非空子集 23 for(int s = u; s; s = (s - 1) & u) { 24 // s 是 u 的一個非空子集 25 int t=s;
26 cout<<"{"; 27 for(int i=0; i<=8; i++){ 28 if(t & (1<<i)) 29 cout<<i<<","; 30 } 31 cout<<"}"; 32 cout<<endl; 33 } 34 35 return 0; 36 }

寫法二:相關連結https://www.cnblogs.com/tflsnoi/p/11946748.html

 1 #include<bits/stdc++.h>
 2 using namespace std;
 3 int a[10];
 4 void print_subset(int n)
 5 {
 6     for(int i=0; i<(1<<n); i++){
 7         for(int j=0; j<n; j++)
 8             if(i&(1<<j))
 9                 cout<<a[j]<<" ";
10         cout<<endl;
11     }
12 }
13 int main()
14 {
15     int n;
16     cin>>n;
17     for(int i=0; i<n; i++)
18         cin>>a[i];
19     print_subset(n);
20     return 0;
21  }

時間複雜度:n*2n