# 一、排列问题

## 1.3C++实现

#include <iostream>
using namespace std;
bool arrsame(int* arr, int len, int num) {
int i;
for (i = 0; i < len; i++)
if (arr[i] == num)
break;
return i != len;
}
bool next_perm(int* perm, const int k, const int n) {
int i = k - 1;
do
perm[i]++;
while (arrsame(perm, i, perm[i]) || (perm[i] >= n && i--));
if (perm[0] >= n)
return 0;
for (int num = 0, seat = i + 1; seat < k; num++)
if (!arrsame(perm, i + 1, num))
perm[seat++] = num;
return 1;
}
int main() {
int n, k;
cout << "perm(n,k):" << endl;
cin >> n >> k;
if (n < k || k <= 0)
return 0;
int* perm = new int[k];
for (int i = 0; i < k; i++)
perm[i] = i;
do
for (int i = 0; i < k; cout << ((++i < k) ? ',' : '\n'))
cout << perm[i] + 1;
while (next_perm(perm, k, n));
delete[] perm;
return 0;
}


# 二、组合问题

## 2.3C++ 实现

//循环法实现
/***********************/
/** This is C++ code. **/
/**   Comb  Example   **/
/***********************/

#include <iostream>
using namespace std;
bool next_comb(int* comb, const int n, const int k) {
int i = k - 1;
const int e = n - k;
do
comb[i]++;
while (comb[i] > e + i && i--);
if (comb[0] > e)
return 0;
while (++i < k)
comb[i] = comb[i - 1] + 1;
return 1;
}
int main() {
int n, k;
cout << "comb(n,k):" << endl;
cin >> n >> k;
if (n < k || k <= 0)
return 0;
int* comb = new int[k];
for (int i = 0; i < k; i++)
comb[i] = i;
do
for (int i = 0; i < k; cout << ((++i < k) ? ',' : '\n'))
cout << comb[i] + 1;
while (next_comb(comb, n, k));
delete[] comb;
return 0;
}


©️2019 CSDN 皮肤主题: 书香水墨 设计师: CSDN官方博客