Method One: Incremental construction method
Understanding recursion has to understand what a function does.
#include <cstdio>void print_subset (int n,int *a,int cur) { printf ("{"); for (int i=0;i<cur;i++) printf ("%d", A[i]); printf ("}\n"); int mi=cur?a[cur-1]+1:0; Use dictionary order to avoid duplicate printing for (int i=mi;i<n;i++) { a[cur]= }}int main () {int n; int a[ 10]={}; scanf ("%d",&N); Print_subset (n,a,0);//initially a subset of 0 elements is stored in a, starting to recursively print return 0;}
Method Two: Bit vector method
Enumeration of each bit or not, the complexity is slightly higher than the method, but better understood, because the output is the same as the whole line of thinking, full n-bit output.
#include <cstdio>int a[10];void print_subset (int n,int *b,int cur) { if (cur==n) { printf ("{"); for (int i=0;i<n;i++) if (B[i]) printf ("%d", A[i]); printf ("}\n"); } else }}int main () {int n; int b[10]={}; scanf ("%d",&N); for (int i=0;i<n;i++) a[i]= I Print_subset (n,b,0); return 0;}
The disadvantage is that the output is not in dictionary order.
Method 3:2 Binary method
A little thought will find that the two methods are in fact corresponding to the binary system.
#include <cstdio>int a[10];void print_subset (int n,int b) { printf ("{"); for (int i=0;i<n;i++) if (b& (1<<i)) printf ("%d", A[i]); printf ("}\n");} void p_s (int}int main () {int n; scanf ("%d",&N); for (int i=0;i<n;i++) a[i]=i; p_s (n); ret Urn 0;}
The advantage of this method is that the code is simple.
Note: The output order of the above three methods is different.
Three algorithms for enumerating all subsets-"Getting Started with algorithms"