從數字集合 {1,2,3,4} 中選取 3 個互不相同的數字,組成三位數。求總數與列舉所有數字。
數學答案:P(4,3) = 4×3×2 = 24 個。
#include <stdio.h>
int main()
{
int count = 0;
for (int i = 1; i <= 4; i++) // 百位
for (int j = 1; j <= 4; j++) // 十位
if (i != j)
for (int k = 1; k <= 4; k++) // 個位
if (k != i && k != j) {
printf("%d%d%d\n", i, j, k);
count++;
}
printf("共 %d 個\n", count);
return 0;
}
123 124 132 134 142 143
213 214 231 234 241 243
312 314 321 324 341 342
412 413 421 423 431 432
共 24 個
若元素個數 n、選取 r 為變數,三重迴圈不再適用,需用遞迴回溯或下一個排列算法:
// 回溯法框架
void permute(int* a, int n, int r, int depth, int* used, int* cur) {
if (depth == r) { print(cur); return; }
for (int i = 0; i < n; i++)
if (!used[i]) {
used[i] = 1; cur[depth] = a[i];
permute(a, n, r, depth+1, used, cur);
used[i] = 0;
}
}
#include <algorithm>
#include <iostream>
int main() {
int a[] = {1,2,3,4};
do { for(int x:a) std::cout<<x; std::cout<<'\n'; }
while(std::next_permutation(a, a+4));
}
k!=i && k!=j 確保三數互異count 驗證 P(n,r) 公式