编程算法 - 计算一个数的所有组合数 代码(C++)
2015-01-19 17:06
295 查看
计算一个数的所有组合数 代码(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
/*
* Combination.cpp
*
* Created on: 2014.6.9
* Author: Spike
*/
/*eclipse cdt, gcc 4.8.1*/
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void deleteOneNum (std::string& _num, std::size_t _n) {
if (_n >= _num.length()) {
return;
}
string temp (_num.substr(_n+1));
_num = _num.substr(0, _n) + temp;
}
void combination (std::string _num, std::string _buff,
std::vector<std::string>& _result)
{
if (_num.length() <= 0) {
_result.push_back(_buff);
}
for (std::size_t i=0; i<_num.length(); ++i) {
std::string temp (_num);
deleteOneNum(temp, i);
combination(temp, _buff+_num[i], _result);
}
}
int main (void) {
std::string num("4123");
std::vector<std::string> result;
combination(num, "", result);
for (std::size_t i=0; i<result.size(); ++i) {
std::cout << result[i] << std::endl;
}
return 0;
}
输出:
[plain] view
plaincopy
4123
4132
4213
4231
4312
4321
1423
1432
1243
1234
1342
1324
2413
2431
2143
2134
2341
2314
3412
3421
3142
3124
3241
3214
相关文章推荐
- 编程算法 - 计算一个数的所有组合数 代码(C++)
- C++和C代码:删除字符串中所有前导空格和所有后导空格,单词之间最多只留一个空格
- C++ 一个统计文件夹下所有代码文件行数的小工具
- 求解一个字符串的所有字符的组合 Java代码
- 【C++】计算所有小于N的勾股数组合,可以写入txt文件保存,每组占一行。
- 有一个纯字符串,编写一段代码,列出其所有字符的大小写组合 如 :字符串“ji”,字母组合['ji','jI','Ji','JI'] 即每个字符的大小写组合
- C/C++——读入一系列由空白分割的(名字,值)对,其中每个名字是由空白分隔开的一个单词,值是一个整数或者一个浮点值, 计算并打印出对应于每个名字的所有值之和与平均值..
- 怎么计算一个集合的幂集(所有子集形成的集合)的长度?涉及组合数学基础
- 计算一个项目工程中所有包下面的代码行数
- 有一个很大的整数list,需要求这个list中所有整数的和,写一个可以充分利用多核CPU的代码,来计算结果(转)
- 最近距离 已知平面上的若干点的位置,存入一个List中。现在需要计算所有这些点中, 距离最近的两个点间的最小距离。请补全缺失的代码。
- 判断一个有向图中是否存在一个环(C++代码)
- 计算一个数组所有元素之和(方法总结)
- 将一个txt文档中所有字符读入一个数组中的代码
- VS2005发布网站问题及"aspnet_merge.exe”已退出,代码为 1的错误以及所有代码文件生成一个dll
- 一个计算周次和本周时间范围的代码(c#)
- HR--一个员工的所有主数据(PA*)克隆到一个新员工的程序代码
- 一个计算周次和本周时间范围的代码(c#)[转]
- HR--一个员工的所有主数据(PA*)克隆到一个新员工的程序代码
- 程序员面试题精选(44):整数分割(即求一个数N由小于等于N的数相加所得的所有组合)