C++ STL 全排列函数详解
STL方法:
#include <iostream>
#include <algorithm>
using namespace std;
int main ()
{
int arr[] = {3,2,1};
cout<<"用prev_permutation对3 2 1的全排列"<<endl;
do
{
cout << arr[0] << ' ' << arr[1] << ' ' << arr[2]<<'\n';
}
while ( prev_permutation(arr,arr+3) ); ///获取上一个较大字典序排列,如果3改为2,只对前两个数全排列
int arr1[] = {1,2,3};
cout<<"用next_permutation对1 2 3的全排列"<<endl;
do
{
cout << arr1[0] << ' ' << arr1[1] << ' ' << arr1[2] <<'\n';
}
while ( next_permutation(arr1,arr1+3) ); ///获取下一个较大字典序排列,如果3改为2,只对前两个数全排列
///注意数组顺序,必要时要对数组先进行排序
return 0;
}
全排列算法:
调试代码。至于讲解没时间写了,看看原博客的吧。
#include <iostream>
using namespace std;
template <typename T>
inline void swap(T* array, unsigned int i, unsigned int j)
{
T t = array[i];
array[i] = array[j];
array[j] = t;
}
/*
* 递归输出序列的全排列
*/
void FullArray(char* array, size_t array_size, unsigned int index)
{
if(index >= array_size)
{
for(unsigned int i = 0; i < array_size; ++i)
{
cout << array[i] << ' ';
}
cout << '\n';
return;
}
for(unsigned int i = index; i < array_size; ++i)
{
swap(array, i, index);
FullArray(array, array_size, index + 1);
swap(array, i, index);
}
}
int main()
{
char array[5]={'a','b','c','d','e'};
FullArray(array,5,0);
return 0;
}
全排列和全组合实现
全组合:
这些结果的位图值都是 1,2…2^n-1。所以从值 1 到值 依次输出结果:
001
,010
,011
,100
,101
,110
,111
。对应输出组合结果为:a
,b
,ab
,c
,ac
,bc
,abc
。
#include<stdio.h>
#include<string.h>
void Combination(char *str)
{
if(str == NULL)
return ;
int len = strlen(str);
int n = 1<<len;
for(int i=1;i<n;i++) //从 1 循环到 2^len -1
{
for(int j=0;j<len;j++)
{
int temp = i;
if(temp & (1<<j)) //对应位上为1,则输出对应的字符
{
printf("%c",*(str+j));
}
}
printf("\n");
}
}
void main()
{
char str[] = "abc";
Combination(str);
}
C++ bitset 常用函数及运算符
#include <iostream>
#include <bitset>
using namespace std;
int main() {
unsigned short short1 = 4;
bitset<16> bitset1{short1}; // the bitset representation of 4
cout << bitset1 << endl; // 0000000000000100
unsigned short short2 = short1 << 1; // 4 left-shifted by 1 = 8
bitset<16> bitset2{short2};
cout << bitset2 << endl; // 0000000000001000
unsigned short short3 = short1 << 2; // 4 left-shifted by 2 = 16
bitset<16> bitset3{short3};
cout << bitset3 << endl; // 0000000000010000
}