zoukankan      html  css  js  c++  java
  • C++ 求枚举排列的两种方法

    枚举排列常用的方法有两种:一是递归枚举,二是用STL中的next_permutation。

    1.枚举递归:

    void print_permutation(int n,int *p,int *A,int cur){
    	if(cur == n){
    		for(int i = 0;i < n;i++)	cout << A[i] << " ";
    		cout << endl;
    	}
    	else for(int i = 0;i < n;i++){
    		int c1 = 0,c2 = 0;
    		for(int j = 0;j < cur;j++)	if(A[j] == p[i])	c1++;
    		for(int j = 0;j < n;j++)	if(p[i] == p[j])	c2++;
    		if(c1 < c2){
    			A[cur] = p[i];
    			print_permutation(n,p,A,cur+1);
    		}
    	}
    }

    上述代码中c1指的是已经出现的元素(p[i])个数,c2指的是一共有几个元素。

    2.next_permutation:

        头文件:#include<algorithm>

        原型:bool next_permutation(iterator begin,iterator end);

    • 已排好序的数组
    • 每次调用在原数组进行下一次排列
    • 如果当前序列不存在下一个排列时,返回false否则返回true

    用法如下:

    #include<iostream>
    #include<algorithm>
    using namespace std;
    int main()
    {
    	int n,p[10];
    	cin >> n;
    	for(int i = 0;i < n;i++)	cin >> p[i];
    	sort(p,p+n);
    	do{
    		for(int i = 0;i < n;i++)	cout << p[i] << " ";
    		cout << endl;
    	}while(next_permutation(p,p+n));
    	return 0;
    }

  • 相关阅读:
    Java8新特性3 Stream
    注解
    Base64编码
    代理
    Cglib
    快照
    Java安全模式
    Hibernet缓存详解
    中文文档
    JDK1.8时间日期函数
  • 原文地址:https://www.cnblogs.com/long98/p/10352239.html
Copyright © 2011-2022 走看看