编程算法 - 计算一个数的所有组合数 代码(C++)

计算一个数的所有组合数 代码(C++)


本文地址: http://blog.csdn.net/caroline_wendy


计算一个数的组合数, 使用递归进行求解. 

如果计算3位的组合数, 首先任选固定一位, 然后计算其余两位的组合数, 最后组合至一起. 如 1 + [23, 32] = 123, 132;

在固定其余位数, 如 2 + [13, 31] = 213, 231;  3 + [12, 21] = 312, 321;


程序分为两步分, 一个删除任意位置的一个元素, 一个是递归求解组合数.


代码:

[cpp]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. /* 
  2.  * Combination.cpp 
  3.  * 
  4.  *  Created on: 2014.6.9 
  5.  *      Author: Spike 
  6.  */  
  7.   
  8. /*eclipse cdt, gcc 4.8.1*/  
  9.   
  10. #include <iostream>  
  11. #include <vector>  
  12. #include <string>  
  13.   
  14. using namespace std;  
  15.   
  16. void deleteOneNum (std::string& _num, std::size_t _n) {  
  17.     if (_n >= _num.length()) {  
  18.         return;  
  19.     }  
  20.     string temp (_num.substr(_n+1));  
  21.     _num = _num.substr(0, _n) + temp;  
  22. }  
  23.   
  24. void combination (std::string _num, std::string _buff,  
  25.         std::vector<std::string>& _result)  
  26. {  
  27.     if (_num.length() <= 0) {  
  28.         _result.push_back(_buff);  
  29.     }  
  30.   
  31.     for (std::size_t i=0; i<_num.length(); ++i) {  
  32.         std::string temp (_num);  
  33.         deleteOneNum(temp, i);  
  34.         combination(temp, _buff+_num[i], _result);  
  35.     }  
  36. }  
  37.   
  38. int main (void) {  
  39.     std::string num("4123");  
  40.     std::vector<std::string> result;  
  41.     combination(num, "", result);  
  42.     for (std::size_t i=0; i<result.size(); ++i) {  
  43.         std::cout << result[i] << std::endl;  
  44.     }  
  45.     return 0;  
  46. }  

输出:

[plain]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. 4123  
  2. 4132  
  3. 4213  
  4. 4231  
  5. 4312  
  6. 4321  
  7. 1423  
  8. 1432  
  9. 1243  
  10. 1234  
  11. 1342  
  12. 1324  
  13. 2413  
  14. 2431  
  15. 2143  
  16. 2134  
  17. 2341  
  18. 2314  
  19. 3412  
  20. 3421  
  21. 3142  
  22. 3124  
  23. 3241  
  24. 3214  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值