排列、组合、集合3.2

3.2 用字典顺序把一个集合的所有子集都找出来

 1 #include <iostream>
 2 #include <bitset>
 3 #include <stack>
 4 
 5 using namespace std;
 6 
 7 const int num_item = 5;
 8 /// a = {1,2,3};
 9 struct dataEncapsule
10 {
11     int item;
12     int childNum;
13 };
14 
15 void printAllSets(stack<dataEncapsule> items);
16 void printRecursive(stack<dataEncapsule> items);
17 
18 void main()
19 {
20     stack<dataEncapsule> items;
21     dataEncapsule currentItem;
22     for(int i = 0; i < num_item; i++)
23     {
24         currentItem.item = i;
25         currentItem.childNum = num_item - currentItem.item - 1;
26         items.push(currentItem);
27         printAllSets(items);
28         while(!items.empty())
29         {
30             currentItem = items.top();
31             if(currentItem.childNum == 0)
32             {
33                 items.pop();
34             } else {
35                 currentItem.childNum--;
36                 items.pop();
37                 items.push(currentItem);
38                 currentItem.item = num_item - currentItem.childNum - 1;
39                 currentItem.childNum = num_item - currentItem.item - 1;
40                 items.push(currentItem);
41                 printAllSets(items);
42             }
43         }
44     }
45     cout << "is my answer right?\n";
46     
47 }
48 
49 void printAllSets(stack<dataEncapsule> items)
50 {
51     ///sum  num_item    
52     cout << "";    
53         printRecursive(items);
54     cout << " }";
55     cout << "\n";
56 }
57 
58 void printRecursive(stack<dataEncapsule> items)
59 {
60     if(items.empty())
61     {
62         return;
63     }
64     dataEncapsule item = items.top();
65     items.pop();
66     printRecursive(items);
67     if(!items.empty())
68     {
69         cout << ",";
70     }
71     cout << item.item + 1;    
72 }

posted on 2008-11-20 16:22 walking snail 阅读(80) 评论(0)  编辑 收藏 引用 所属分类: 算法

导航

<2025年8月>
272829303112
3456789
10111213141516
17181920212223
24252627282930
31123456

统计

常用链接

留言簿

随笔分类

文章分类(13)

文章档案(16)

相册

搜索

最新评论