AcWing 92. 递归实现指数型枚举

题目链接:https://www.acwing.com/problem/content/description/94/


题意:从 n 个数中选取数字,输出所有的选取可能

idea:枚举所有取数可能,就一简单的DFS,不过题解用二进制表示状态,着实巧妙

我的DFS:

 1 #include <iostream>
 2 #include <cstdio>
 3 
 4 using namespace std;
 5 const int N = 16;
 6 int n, a[16];
 7 bool st[16];
 8 
 9 void dfs(int num)
10 {
11     if (num > n)
12     {
13         for (int i = 1; i <= n; i ++ )
14             if (st[i])  cout << i << " ";
15         cout << endl;
16         return;
17     }
18     st[num] = true;
19     dfs(num + 1);
20     st[num] = false;
21     dfs(num + 1);
22 }
23 
24 int main()
25 {
26     cin >> n;
27     dfs(1);
28     return 0;
29 }
View Code

大佬(秦淮岸)的位运算+递归深度优先搜索

用一个数的二进制的每一位表示选取状态

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 int n;
 4 void dfs(int x,int now)
 5 {
 6     if (x>n)
 7         return ;
 8     if (x==n)
 9     {
10         for (int i=1;i<=n;i++)
11             if (now>>(i-1) & 1)
12                cout<<i<<" ";
13         puts("");
14     }
15     dfs(x+1,now<<1 | 1);
16     dfs(x+1,now<<1);
17 }
18 int main()
19 {
20     cin>>n;
21     dfs(0,0);
22 }
View Code

 

 

 

posted @ 2019-12-04 22:32  chuyds  阅读(208)  评论(0编辑  收藏  举报