C++ 全排列函数 next_permutation与prev_permutation
C++ STL中提供了next_permutation与prev_permutation可以获取数字或者是字符的全排列,其中next_permutation提供升序、prev_permutation提供降序。
1.next_permutation(first,last)
说明:对[first,last)区间进行排列,第一次输出当前的排列顺序,例如:1234,第二次输出比第一次大的下一种排列,则为1243(若为数组,则通过数字比较来判断大小,若为字符串,则通过ASCII码来比较大小)。
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int a[100];
int n=0,i;
while(cin>>a[n])
n++;
sort(a,a+n);
//输出升序的全排列则应将最初的数组排为最小顺序
//如1 4 3 2 ,则应先排为1 2 3 4 使next_premutation()
//正常输出
do
{
for(i=0;i<n-1;i++)
cout<<a[i];
cout<<a[i]<<endl;
}while(next_permutation(a,a+n));
return 0;
}
2.next_permutation( first , last , cmp)
说明:我们可以通过改变cmp()函数来改变next_permutation()函数产生的到底是升序全排列还是,降序全排列。在不写cmp()函数时,next_permutation()默认为升序全排列。
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a>b;//a>b为降序,a<b为升序。
}
int main()
{
int a[100];
int n=0,i;
while(cin>>a[n])
{
n++;
}
sort(a,a+n,cmp);//sort()也应该为降序。
do
{
for(i=0;i<n-1;i++)
cout<<a[i];
cout<<a[i]<<endl;
}while(next_permutation(a,a+n,cmp));//输出降序全排列
return 0;
}
3.prev_permutation( first , last )与prev_permutation( first , last , cmp)的用法与前两项相同,这里就不过多赘述。
4.用next_permutation()对字符串进行排序。
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
int main()
{
string str;
cin>>str;
sort(str.begin(),str.end());
do
{
cout<<str<<endl;
}while(next_permutation(str.begin(),str.end()));
//原理相同。
return 0;
}
4.题目:字符的全排列(顺序:’A’<’a’<’B’<’b’<…<’Z’<’z’)。
#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int val(char c) // 按照'A'<'a'<'B'<'b'<...<'Z'<'z'的顺序,每个字母赋一个固定的权值。
{
if(c >= 'A' && c <= 'Z')
return 2 * (c - 'A');
else
return 2 * (c - 'a') + 1;
}
bool cmp(char a, char b)
{
return val(a) < val(b);
}
int main()
{
char str[100];
cin >> str;
int n = strlen(str);
sort(str, str + n, cmp);
do
{
cout << str << endl;
}
while(next_permutation(str, str + n, cmp));
return 0;
}