全排列函数

一:next_permutation()函数,作用是输出所有比当前排列  排列大的排列(顺序为由小到大排)

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	string str;
	cin>>str;
	while(next_permutation(str.begin(),str.end()))
	  cout<<str<<endl;
   	return 0;
}
/*或者写为:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main(){
	char str[100];
        cout<<"请输入原序列:";
	cin>>str;
	int len=strlen(str);
	while(next_permutation(str,str+len)){
		 cout<<str<<endl;
	}
	
	return 0;
}

*/

如: 

二:perv_permutation()函数,作用是输出比当前排列小的排列      (顺序:从大到小)

#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
int main(){
	string str;
	cout<<"请输入原序列:" ; 
	cin>>str;
	while(prev_permutation(str.begin(),str.end()))
	  cout<<str<<endl;
	return 0;
}
/*  或写为
#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int main()
{
	char str[100];
	cout<<"请输入原序列:" ; 
	cin>>str;
	 int len=strlen(str);
	while(prev_permutation(str,str+len))
	{
		 cout<<str<<endl;
	}
	
	return 0;
}
   
*/

如: 

 

如果要得到几个数的全排列,还可以对上方的函数进行一些更改
比如对于next_permutation()函数,它只对比自己大的排列起作用,所以可以对输入的序列进行由小到大的排序,因为最后的总个数不包含第一个最小的那个序列,所以要在最后的总数上加1,才是这几个数进行全排列的结果。
代码:

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;
int cmp(char a,char b)
{
	return a<b;
}
int main()
{
	char str[100];
	int sum=0;
	cout<<"请输入序列:";
	cin>>str;
	 int len=strlen(str);
	 sort(str,str+len,cmp); 
	while(next_permutation(str,str+len))
	{
		 cout<<str<<endl;
		 sum++;
	}
	cout<<sum<<endl;
	return 0;
}

如:

 

 

  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值