枚举排列

1. 1-N 全排列

#include <iostream> using namespace std; #define N 1001 int rcd[N]; int used[N]; int num[N]; int n; void permutation(int l) { if(l == n) { for(int i = 0; i < n; i++) { cout << rcd[i] << " "; } cout << endl; } else { for(int i = 0; i < n; i++) { if (!used[i]) { used[i] = 1; rcd[l] = num[i]; permutation(l + 1); used[i] = 0; } } } } int readData() { int i; if( scanf("%d", &n) == EOF) { return 0; } for(int i = 0; i < n; i++) scanf("%d", &num[i]); for(int i = 0; i < n; i++) used[i] = 0; return 1; } int main() { while(readData()) { permutation(0); } }

2. 可重集的排列

方法1: 递归枚举

#include <iostream> using namespace std; #define N 1001 int rcd[N]; int used[N]; int num[N]; int n; int m; void unrepeatPermutation(int l) { if(l == n) { for(int i = 0; i < n; i++) { cout << rcd[i] << " "; } cout << endl; } else { for(int i = 0; i < m; i++) { if (used[i] > 0) { used[i]--; rcd[l] = num[i]; unrepeatPermutation(l + 1); used[i]++; } } } } int readData() { int i, j, val; if( scanf("%d", &n) == EOF) { return 0; } m = 0; for(int i = 0; i < n; i++) { scanf("%d", &val); for(j = 0; j < m; j++) { if(num[j] == val) { used[j]++; break; } } if(j == m) { num[m] = val; used[m] = 1; m++; } } return 1; } int main() { while(readData()) { unrepeatPermutation(0); } }

方法2: next_permutation

// next_permutation #include <iostream> #include <algorithm> using namespace std; int main () { int myints[] = {1,1,2}; cout << "The possible permutations with 3 elements:/n"; sort (myints,myints+3); do { cout << myints[0] << " " << myints[1] << " " << myints[2] << endl; } while ( next_permutation (myints,myints+3) ); return 0; }

运行结果:

The possible permutations with 3 elements: 1 1 2 1 2 1 2 1 1

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值