dfs ZOJ 1711 Sum It Up
这几天学,BFS和DFS算法,参照网上找的程序,对照着写的。
所有的排列组合问题,基本是基于DFS算法的思路而来的
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #include<iostream>
2 using namespace std;
3
4
5 int t;
6 int n;
7 int num[12];
8 int rcd[12];
9 int usedtimes[12];
10 int differentnums;
11 bool isfind = false;
12 void norepeat_combination(int, int);
13 void print(int);
14 int main()
15 {
16 int count = 0;
17 int a;
18 bool flag;
19 //freopen("test.txt","r",stdin);
20 while (cin >> t >> n && !(t==0 && n == 0) )
21 {
22 for (int i = 0; i < n; i++)
23 {
24 usedtimes[i] = 1;
25 }
26 flag = true;
27 for (int i = 0; i < n; i++)
28 {
29 cin >> a;
30 for (int j = 0; j < count; j++ )
31 {
32 if (a == num[j])
33 {
34 flag = false;
35 usedtimes[j]++;
36 }
37 }
38 if (flag)
39 {
40 num[count] = a;
41 count++;
42
43 }
44 flag = true;
45 }
46
47 n = count;
48 cout << "Sums of " << t << ":" << endl;
49 norepeat_combination(0, 0);
50 if (!isfind)
51 {
52 cout << "NONE" << endl;
53 }
54 isfind = false;
55 count = 0;
56 }
57 return 0;
58 }
59 int sum;
60
61 //生成不重复组合,类似DFS过程
62 void norepeat_combination(int len, int current)
63 {
64 sum = 0;
65 for (int i = 0; i < len; i++)
66 {
67 sum += rcd[i];
68 }
69 if (sum == t)
70 {
71 isfind = true;
72 print(len);
73 }
74 else
75 {
76 for (int i = current; i < n; i++)
77 {
78 if (usedtimes[i])
79 {
80 usedtimes[i]--;
81 rcd[len] = num[i];
82 norepeat_combination(len+1, i);//这里不是i+1,要把所有重复的都用完,才填入下一个不同的数字
83 usedtimes[i]++;
84 }
85 }
86 }
87
88
89 }
90
91 void print(int len)
92 {
93 for (int i = 0; i < len; i++)
94 {
95 cout << rcd[i];
96 if (i != len - 1)
97 {
98 cout << "+";
99 }
100 }
101 cout << endl;
102 }
103
104
105