全排列和排列组合

排列组合

对一组数字进行排列组合,比如1,2,3的排列组合为
1
2
3
1 2
1 3
2 3
1 2 3

代码实现:

#include<iostream>
#include<algorithm>
using namespace std;
int n,tem[1000],a[1000];
void tsort(int start,int length,int num,int a_len,int *a,int *tem)
{
	int i,j;
	for(i=start;i<a_len;i++)
	{
		tem[length-1]=a[i];
		if(length-1==0)
		{
			for(j=num-1;j>=0;j--)
			cout<<tem[j];
			cout<<endl;
		}
		else
		tsort(i+1,length-1,num,a_len,a,tem);
	}
} 
int main()
{
	cin>>n;
	for(int i=0;i<n;i++)
	cin>>a[i];
	sort(a,a+n);
	for(int i=1;i<=n;i++)
	{
		tsort(0,i,i,n,a,tem); 
	}
}

全排列

**这里先说两个概念:“下一个排列组合”和“上一个排列组合”,对序列 {a, b, c},每一个元素都比后面的小,按照字典序列,固定a之后,a比bc都小,c比b大,它的下一个序列即为{a, c, b},而{a, c, b}的上一个序列即为{a, b, c},同理可以推出所有的六个序列为:{a, b, c}、{a, c, b}、{b, a, c}、{b, c, a}、{c, a, b}、{c, b, a},其中{a, b, c}没有上一个元素,{c, b, a}没有下一个元素。

1)next_permutation:求下一个排列组合

a.函数模板:next_permutation(arr, arr+size);
b.参数说明:
  arr: 数组名
  size:数组元素个数
c.函数功能: 返回值为bool类型,当当前序列不存在下一个排列时,函数返回false,否则返回true,排列好的数在数组中存储

d.注意:在使用前需要对欲排列数组按升序排序,否则只能找出该序列之后的全排列数。
    比如,如果数组num初始化为2,3,1,那么输出就变为了:{2 3 1} {3 1 2} {3 2 1}
**
代码实现:

#include <iostream>
#include <algorithm>
using namespace std;
int arr[1000],arr1[1000];
int main ()
{
    int m;
    cin>>m;
    for(int i=0;i<m;i++)
    cin>>arr1[i];
    sort(arr1,arr1+m);
    cout<<"用next_permutation对数组arr1的全排列"<<endl;
    do
    {
         for(int i=0;i<m;i++)
        cout<<arr1[i]<<"   ";
        cout<<endl;
    }
    while ( next_permutation(arr1,arr1+m) );      ///获取下一个较大字典序排列,如果3改为2,只对前两个数全排列
    ///注意数组顺序,必要时要对数组先进行排序

    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值