库函数求全排列

本文深入探讨了C++中next_permutation函数的使用方法,包括如何生成全排列,以及如何处理字符串和自定义排序规则。通过具体示例,如数字数组和字符串的全排列输出,展示了next_permutation函数的强大功能。

上级排列:prev_permutation(start, end)                //求的是当前排列的上一个排列

下级排列:next_permutation(start, end)                //求的是当前排列的下一个排列

对于“上一个”和“下一个”,它们为字典序的前后,就是对于当前序列Pn,他的下一个序列Pn+1,不存在另外的Pm,使得Pn<Pm<Pn+1。

字典序:不同排列的先后关系是从左——>右逐个比较对应的数字的先后来决定的。

例如:——对于6个数字的排列123456和123465,按照字典序的定义,123456排在123465的前面。

           ——比较单词(lead和leader),把短的排前面。

对于next_permutation函数,其原型为:

#include<algorithm>

bool next_permutation(iterator start,  iterator end)

当当前序列不存在下一个排列时,返回false,否则返回true。

对于这两个函数一般和do ~ while搭配。

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
	int num[3] = {1, 2, 3};
	do{
		printf("%d %d %d\n", num[0], num[1], nu[2]);
	}while(next_permutation(num, num+3));
	return 0;
} 

输出结果:

1 2 3
1 3 2
2 1 3
2 3 1
3 1 2
3 2 1

如果把while(next_permutation(num, num+3))中的3改为2,则输出结果为:

1 2 3
2 1 3

可以从中看出这个函数是对数组num中的前n个元素进行全排列,同时并改变num[ ]的值 。

如果把初始数组改为:int num = {2, 3, 1};则输出结果为:

2 3 1
3 1 2
3 2 1

可以从中看出这个结果是在初始值往后的全排列。

 

如果输入的是字符串,原代码改为:

char ch[50];
scanf("%s", ch);
int n = strlen(ch);
sort(ch, ch+strlen(ch));
do{
	puts(ch);
}while(next_permutation(ch, ch+n));

样例:题目链接:https://www.51nod.com/Challenge/Problem.html#!#problemId=1384

代码实现:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int main()
{
	char s[12];
	scanf("%s", s);
	int l = strlen(s);
	sort(s, s+l);
	do{
		puts(s);
	}while(next_permutation(s, s+l));
	return 0;
}

题目链接:http://poj.org/problem?id=1256

代码实现:

#include<stdio.h>
#include<iostream>
#include<algorithm>
#include<string.h>
using namespace std;
int val(char c)
{
	// 按照'A'<'a'<...<'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()
{
	int T;
	char str[20]; 
	scanf("%d", &T);
	while(T--)
	{
		cin >> str;
		int n = strlen(str);
		sort(str, str+n, cmp);
		do{
			cout << str << endl;
		}while(next_permutation(str, str+n, cmp));
	} 
	return 0;
}

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值