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

来源:互联网 发布:小站教育 知乎 编辑:程序博客网 时间:2024/05/29 14:29

计算一个数的所有组合数 代码(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 plaincopy在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 plaincopy在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
原创粉丝点击