一组数的全排列和组合程序实现

显示一组数的全排列和组合程序:

 1 void print(const std::vector<int>& s)
 2 {
 3     static int n = 1;
 4     printf("%d:", n++);
 5     printf("[");
 6     for (int i = 0; i < s.size(); i++)
 7         printf(" %d ", s[i]);
 8     printf("]\n");
 9 }
10 
11 void permutation(std::vector<int>& v, int beg, int end)
12 {
13     if (beg > end) {
14         print(v);
15         return;
16     }
17     for (int i = beg; i <= end; i++) {
18         std::swap(v[i], v[beg]);
19         permutation(v, beg+1, end); // pleate note, here always beg+1, not i+1
20         std::swap(v[i], v[beg]);
21     }
22 }
23 
24 void pm(std::vector<int>& v)
25 {
26     std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " "));
27     printf("\nfull permulation are:\n");
28     permutation(v, 0, v.size()-1);
29 }
30 
31 void print(const std::vector<int>& v, int beg, int end)
32 {
33     static int n = 1;
34     printf("%d:", n++);
35     printf("[");
36     std::copy(v.begin()+beg, v.begin()+end+1, std::ostream_iterator<int>(std::cout, " "));
37     printf("]\n");
38 }
39 
40 void fullcombination(std::vector<int>& v)
41 {
42     printf("full combination are:\n");
43     for (unsigned int i = 0; i < v.size(); i++) {
44         print(v, i, i);
45         for (unsigned int j = i+1; j < v.size(); j++) {
46             for (int k = 0; k < v.size()-j; k++) {
47                 std::swap(v[j+k], v[j]);
48                 print(v, i, j);
49                 std::swap(v[j+k], v[j]);
50             }
51         }
52     }
53 }
54 

 

 

转载于:https://www.cnblogs.com/zerolee/archive/2012/06/17/2552490.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值