例题:枚举排列
来源:互联网 发布:阿里云国际版注册地址 编辑:程序博客网 时间:2024/05/19 13:57
枚举排列常见的方法有两种:一种是递归枚举,而是用STL中的next_permutation
【1】生成可重集的排列
#include<stdio.h>#include<string.h>#include<stdlib.h>int p[20];int cmp(const void *a, const void *b){return *(int *)a - *(int *)b;}void print_permutation(int n, int *a, int cur){if (cur == n){for (int i = 0; i < n; i++)printf("%d ", a[i]);printf("\n");}else{for (int i = 0; i < n; i++){if (!i || p[i] != p[i - 1])//防止重复的数多次输出,需要先排序{int c1 = 0, c2 = 0;//为了顺利输出存在相同的情况for (int j = 0; j < cur; j++)if (a[j] == p[i])c1++;//寻找现排列中与原排列相同的个数c1for (int j = 0; j < n; j++)if (p[j] == p[i])c2++;//原排列中自身重复的个数c2if (c1 < c2)//c1<c2即可递归{a[cur] = p[i];print_permutation(n, a, cur + 1);}}}}}int main(){int a[20];int n;scanf("%d", &n);for (int i = 0; i < n; i++)scanf("%d", &p[i]);qsort(p, n, sizeof(p[0]), cmp);print_permutation(n, a, 0);return 0;}
【2】下一个排列
#include<cstdio>#include<algorithm>using namespace std;int main(){int n, p[10];scanf("%d", &n);for (int i = 0; i < n; i++)scanf("%d", &p[i]);sort(p, p + n);do {for (int i = 0; i < n; i++)printf("%d ", p[i]);printf("\n");} while (next_permutation(p, p + n));//直接while不会输出自身(输入的那个序列)return 0;}
0 0
- 例题:枚举排列
- 用DFS实现排列和组合两种枚举方式【附带例题HDU1015,POJ1753题解】
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 枚举排列
- 6.4例题--排列--1833
- 蓝桥杯-排列(例题)
- lvs -dr
- UML-组合
- Ajax技术
- Stein算法(求两个数最大公约数)
- 剑指offer面试题14(Java版):调整数组顺序使奇数位于偶数的前面
- 例题:枚举排列
- 欢迎使用CSDN-markdown编辑器
- Cocos2d-x3.8.1制作愤怒的小鸟
- 光纤交换机:
- Elasticsearch2.x 全文检索之——Match Query
- [BZOJ3643]Phi的反函数(数学相关+搜索)
- 解决rhel7录屏只能三十秒的执行脚本
- 非递归求集合的幂集
- 中国剩余问题(简介+详解)