1 排列问题
1.1 递归算法
例如有三个数{1,2,3},可以看成1+{2,3}的排列,2+{1,3}的排列,3+{1,2}的排列。
1+{2,3}的排列有1,2,3和1,3,2。//这种方法规避不了含有相同元素的排列问题
#include <iostream>
#include <algorithm>
using namespace std;
void myswap(int& a,int& b){
int t = a;
a = b;
b = a;
}
void myperm(int* arr,int k,const int len){
if(k == len){ //排列到最后一个数,已经全部排列完,可以打印出来
for(int i = 0;i <= len;i++)
cout<<arr[i]<<" ";
cout<<endl;
}else{
for(int i = k;i <= len;i++){
myswap(arr[i],arr[k]);
myperm(arr,k+1,len);
myswap(arr[i],arr[k]);
}
}
}
/*
1 2 3 4 //排到第三个元素时
1 2 4 3 //第三个和第四个交换一下,(排完之后交换回来)
1 3 2 4 //排列到第二个元素时,第二个元素和第三个元素交换
1 3 4 2 //上一种情况的子情况,交换第三个和第四个元素
1 4 3 2
1 4 2 3
2 1 3 4
2 1 4 3
2 3 1 4
2 3 4 1
2 4 3 1
2 4 1 3
...
4 1 3 2
4 1 2 3
*/
void test(){
int arr[4] = {1,2,3,4};
myperm(arr,0,3);
}
int main(){
test();
return 0;
}
1.2 调用next_permutation
next_permutation属于<algorithm>中的一个算法函数,返回值为bool,意为下一个大一点的排列,所以排列前必须要进行排序。与之对应的是pre_permutation,意为下一个小一点的排列。//这种方法可以规避相同元素的排列问题。
#include <iostream>
#include <algorithm>
using namespace std;
void test(){
int arr[4] = {1,3,2,4}; //随机乱序
sort(arr,arr+4); //必须先排好序,因为用的是next_permutation,所有升序
do{
for(int i = 0;i < 4;i++)
cout<<arr[i]<<" ";
cout<<endl;
}while(next_permutation(arr,arr+4));
}
int main(){
test();
return 0;
}
2 组合问题
2.1 求组合数
如果调用中学学的公式,可以求出组合数,但当数过大时,进行乘法非常容易越界。Cmn代表从n个元素中选出m个元素。
C11 = 1;
C12 = 2; C22 = 1;
C13 = 3;C23 = 3; C33 = 1;
...
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1 (从第二个开始算,分别代表C14,C24,C34,C44)
。。。 //其实就是一个杨辉三角
//组合数
#include <iostream>
#include <algorithm>
using namespace std;
void test() {
const int MAXN = 100; //假设n最大为100
int arr[MAXN + 1][MAXN + 1] = { 0 };
arr[0][0] = 1; //第0行第0列初始化
for (int i = 0; i <= MAXN; i++) {
arr[i][0] = 1;
}
for (int i = 1; i <= MAXN; i++) {
for (int j = 1; j <= i; j++) {
arr[i][j] = arr[i - 1][j - 1] + arr[i - 1][j]; //左上方元素加上最上方元素
}
}
//int n = 4;
//int m = 2;
//cout << arr[n][m] << endl;
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
cout << arr[i][j] << " ";
}
cout << endl;
}
}
int main() {
test();
//system("pause");
return 0;
}
2.2 求组合的可能情况
如果有n个不重复的的数(含重复的可以用set过滤掉),则可能的组合为2的n次方,每一位代表0或1,0表示不选上,1表示选上。
#include <iostream>
#include <algorithm>
#include <string>
#include <set>
using namespace std;
void getCom(string str, set<string>& ss) {
//set本质是一个红黑二叉树,可以避免重复元素
int len = str.size();
int cmax = 1 << len;
string ts;
for (int i = 1; i < cmax; i++) { //不包括空集
ts.clear();
for (int j = 0; j < len; j++) {
if ((i >> j) & 1) {
ts = ts + str[j];
}
}
ss.insert(ts);
}
}
void test() {
string str = "aac";
set<string> ss;
getCom(str, ss);
for (auto i = ss.begin(); i != ss.end(); i++) {
cout << *i << endl;
}
}
int main() {
test();
system("pause");
return 0;
}