【hihoCoder】每周一题(从week 220开始)

2018/9/17~2018/9/23  week 220

push button I

题目链接:https://hihocoder.com/contest/hiho220/problem/1

有N个按钮,每个按钮都需要被按下一次,一次可以同时按下几个按钮,输出所有按下的方案。但是同时按下12, 和同时按下21是一样的。所以不能有这种同时的重复。

Sample Input

3

Sample Output

1-2-3
1-23
1-3-2
12-3
123
13-2
2-1-3
2-13
2-3-1
23-1
3-1-2
3-12
3-2-1

题解: 直接dfs。 看了题解dfs的方法。

(1)每次选举一个比同组最后一个数字大的数, 避免(3-12 和 3-21) 这种重复的情况

(2)开始一个新的组

 1 #include <iostream>
 2 #include <cstdio>
 3 #include <cstdlib>
 4 #include <string>
 5 #include <cstring>
 6 #include <set>
 7 
 8 using namespace std;
 9 
10 int n;
11 int visit[10];
12 set<string> st;
13 void dfs(int last, int cnt, string str) {
14     //printf("print debug, str: %s 
", str.c_str());
15     if (cnt == n) {
16     //    cout << str << endl;
17     st.insert(str);
18         return;
19     }
20     for (int i = 1; i <= n; ++i) {
21         if (visit[i] == true) { continue; }
22         if (i > last) {
23             visit[i] = true;
24             char c = i + '0';
25             dfs(i, cnt+1, str + c);
26             visit[i] = false;
27         }
28     }
29     if (str.back() != '-') {
30         dfs(-1, cnt, (str + "-"));
31     }
32 }
33 
34 int main() {
35     scanf("%d", &n);
36     memset(visit, 0, sizeof(visit));
37     for (int i = 1; i <= n; ++i) {
38         visit[i] = true;
39         string str = to_string(i);
40         dfs(i, 1, str);
41         visit[i] = false;
42     }
43     for (auto iter = st.begin(); iter != st.end(); ++iter) {
44         cout << *iter << endl;
45     }
46     
47     return 0;
48 }
View Code
原文地址:https://www.cnblogs.com/zhangwanying/p/9689761.html