c++ 全排列

转载自:http://blog.sina.com.cn/s/blog_9f7ea4390101101u.html

头文件: algorithm

int类型的全排列

#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    
    
	int a[3];
	a[0] = 1;
	a[1] = 2;
	a[2] = 3;
	do{
    
    
		cout<<a[0]<<" "<<a[1]<<" "<<a[2]<<endl;
	}while(next_permutation(a,a+3));	 //参数3是指全排列的长度
	return 0;
}

如果存在a之后的排列则返回true,不存在返回false。

char类型的全排列

#include <iostream>
#include <algorithm>
#include <string.h>
using namespace std;
int main()
{
    
    
	char ch[205];
	cin>>ch;
	//eabdc --> abcde
	sort(ch,ch+strlen(ch)); //先升序 
	char *first = ch;
	char *last = ch + strlen(ch); 
	
	do{
    
    
		cout<<ch<<endl;
	}while(next_permutation(first,last));
	return 0;
}

String类型的全排列

寻找下一个全排列

#include <cstdio>
#include <iostream>
#include <algorithm>
using namespace std;

int main()
{
    
    
	string line;
	while(cin>>line && line!="#"){
    
    
		if(next_permutation(line.begin(),line.end()))
			cout<<line<<endl;
		else cout<<"No!"<<endl;
	}
	return 0;
}

正常全排列

#include <iostream>
#include <algorithm>
#include <cstdio>
using namespace std;
int main()
{
    
    
	string line;
	while(cin>>line && line!="#"){
    
    
		sort(line.begin(),line.end());
		do{
    
    
			cout<<line<<endl;
		}while(next_permutation(line.begin(),line.end()));
	}
	return 0;
} 

自定义规则的全排列

#include <bits/stdc++.h>
using namespace std;

int cmp(char a,char b){
    
    
	if(tolower(a)!=tolower(b))
		return tolower(a)<tolower(b);
	else
		return a<b;
}

int main()
{
    
    
	char ch[20];
	while(cin>>ch && ch[0]!='#'){
    
    
		sort(ch,ch+strlen(ch),cmp);
		
		do{
    
    
			printf("%s\n",ch); 
		}while(next_permutation(ch,ch+strlen(ch),cmp));		
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/zhimeng_LQ/article/details/108553349
今日推荐