不同组的组合
有 N 个组,每个组中有不定个元素,从每个组中选择一个元素,例如:
第一组 1 2
第二组 3 4
第三组 5
结果为:
1 3 5
1 4 5
2 3 5
2 4 5
http://topic.csdn.net/u/20100313/23/51e49d61-8a36-47f5-8e3b-20477dafde55.html
1 #include <iostream>
2 #include <string>
3 #include <vector>
4 using namespace std;
5
6 void foo(vector<vector<string> >& result, vector<string>& temp, const vector<vector<string> >& vvs, size_t m)
7 {
8 if (temp.size() >= vvs.size())
9 {
10 result.push_back(temp);
11 for (size_t i = 0; i != temp.size(); ++i)
12 {
13 cout << temp[i] << ' ';
14 }
15 cout << endl;
16 }
17 else
18 {
19 for (size_t i = 0; i != vvs[m].size(); ++i)
20 {
21 temp.push_back(vvs[m][i]);
22 foo(result, temp, vvs, m + 1);
23 temp.pop_back();
24 }
25 }
26 }
27
28 void bar(vector<vector<string> >& result, const vector<vector<string> >& vvs)
29 {
30 vector<string> temp;
31 foo(result, temp, vvs, 0);
32 }
33
34 int main()
35 {
36 vector<vector<string> > vvs;
37 vector<string> vs;
38 vs.push_back("A1");
39 vs.push_back("A2");
40 vvs.push_back(vs);
41 vs.clear();
42 vs.push_back("B1");
43 vs.push_back("B2");
44 vvs.push_back(vs);
45 vs.clear();
46 vs.push_back("C1");
47 vs.push_back("C2");
48 vs.push_back("C3");
49 vvs.push_back(vs);
50 vs.clear();
51 for (size_t i = 0; i != vvs.size(); ++i)
52 {
53 for (size_t j = 0; j != vvs[i].size(); ++j)
54 {
55 cout << vvs[i][j] << ' ';
56 }
57 cout << endl;
58 }
59 cout << endl;
60 vector<vector<string> > result;
61 bar(result, vvs);
62 cout << endl;
63 for (size_t i = 0; i != result.size(); ++i)
64 {
65 for (size_t j = 0; j != result[i].size(); ++j)
66 {
67 cout << result[i][j] << ' ';
68 }
69 cout << endl;
70 }
71 return 0;
72 }
posted on 2011-10-06 13:23
unixfy 阅读(165)
评论(0) 编辑 收藏 引用