AcWing recursively implements exponential enumeration dfs

Randomly select any number from n integers from 1 to n, and output all possible options.

Input format

Enter an integer n.

Output format

One scheme is output per line.

The numbers in the same row must be arranged in ascending order, and two adjacent numbers are separated by exactly 1 space.

For programs that did not select any number, output blank lines.

This question has a custom validator (SPJ), and the order between the lines (different schemes) is arbitrary.

data range

1n15

Sample input:

3

Sample output:

3
2
2 3
1
1 3
1 2
1 2 3
预备知识:
  一个元素数量为n的集合的子集个数是2^n。
  证明:有n个元素,每个元素进行一次判断要不要把它选出来放进子集里,这样判断n次,产生了2^n种不同结果。
搜索的顺序:
  从前往后遍历1~n,依次判断每个数是选还是不选。
 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n;
 4 int st[20]; //标记每一位有没有被选,0表示还没考虑,1表示选,2表示不选 
 5 void dfs(int u) { //u表示当前在判断第几位 
 6     if (u == n + 1) { //如果已经判断完了 
 7         for (int i = 1; i <= n; i++) {
 8             if (st[i] == 1) {
 9                 cout << i << " ";
10             }
11         }
12         cout  << endl;
13         return;
14     }
15     //不选u 
16     st[u] = 2;
17     dfs(u + 1);
18     st[u] = 0; //回溯恢复现场 
19     
20     //选u
21     st[u] = 1;
22     dfs(u + 1);
23     st[u] = 0; //回溯恢复现场 
24 }
25 int main() {
26     cin >> n;
27     dfs(1); //从下标为0开始搜索 
28     return 0;
29 } 

Guess you like

Origin www.cnblogs.com/fx1998/p/12760060.html