全排列函数next_permutation的用法

1  产生n个数的全排列

输入 3   1 0 2
输出  0 1 2   0 2 1   1 0 2   1 2 0   2 0 1   2 1 0

#include <stdio.h>
#include <algorithm>
using namespace std;
int main(){
    int n;
    while(scanf("%d",&n)&&n){
        int a[1000];
        for(int i=0;i<n;i++){
            scanf("%d",&a[i]);
        }
        sort(a,a+n);//可以自行测试一下删除后的结果;next_permutation(a,a+n)作用于排好序的数组/对列中
        do{
            for(int i=0;i<n;i++)
                printf("%d ",a[i]);
            printf("\n");
        }while(next_permutation(a,a+n));
    }
    return 0;
}

函数next_permutation(参数1,参数2)的双参数调用方式,默认是按照字典序产生排列的,并且是从数组中当前的字典序开始依次增大直至到最大字典序。

2 题目就是有一个数n(0<n<10),写出1到n的全排列

输入 多组(m)数据,对每组数n(0<n<10),写出1到n的全排列
输入 2   2  3  (两组数据 分别为2 ,3那么就是寻找1,2 和1,2,3的全排列)

输出 

12 
21 
123
132 
213 
231 
312 
321

#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
Int  i,m,n;
cin>>m;
while(m--)
{
 cin>>n;
 int a[n];
 for(i=0;i<n;i++)
    a[i]=i+1;
do
{
    for(i=0;i<n;i++)
        cout<<a[i];
    cout<<endl;
}
while (next_permutation(a,a+n));//排列组合函数
}
return 0;
}

3 第一行输入整数N(1<N<10)表示多少组测试数据,每组测试数据第一行两个整数 n m (1<n<9,0<m<=n)
样例输入
3
3 1
4 2
3 3
样例输出
1
2
3
12
13
14
21
23
24
31
32
34
41
42
43
123
132
213
231
312
321

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

int main()
{
	int m, n, i, b;
	cin >> b;
	while (b--)
	{
		string a, s1, s2;
		cin >> n >> m;
		for (i = 0; i<n; i++)
			a += i + '1';
		s1 = a.substr(0, m);
		cout << s1 << endl;
	//	next_permutation(a.begin(), a.end());//先给s2一个初值
		do
		{
			s2 = a.substr(0, m);
			if (s1 != s2)
			{
				cout << s2 << endl;
				s1 = s2;
			}
		} while (next_permutation(a.begin(), a.end()));
	}
	return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值