← 回題庫

卷別

資料結構

選擇

國立中央大學 2026 · 考試 · 第 38 題

Given a set of n elements (n≥1n \ge 1), the following code prints out all possible permutations of this set. For example, if the set is {a, b, c}, then the set of permutation is {(a, b, c), (a, c, b), (b, a, c), (b, c, a), (c, b, a), (c, a, b)}.

 1  #include <stdio.h>
 2  #include <string.h>
 3  #define SWAP(A, B) do { char _tmp[sizeof((A))];       \
 4      memcpy(_tmp,&(A),sizeof((A)));                    \
 5      (A)=(B);                                          \
 6      memcpy(&(B),_tmp,sizeof((B)));} while(0)
 7  void perm(char *list, int i, int n) {
 8      int j, temp;
 9      if(i==n){
10          for(j=0;j<=n;j++)
11              printf("%c",list[j]);
12          printf(",");
13      }
14      else {
15          for (j=i;j<=n;j++){
16              SWAP(list[i],list[j]);
17              printf("%d%d,",i,j);  //swap i,j
18              perm(list,i+1,n);
19              printf("%d%d,",j,i);  //swap j,i
20              SWAP(list[j],list[i]);
21          }
22      }
23  }
24  int main(){
25      char str[]="abc";
26      perm(str,0,2);
27      return 0;
28  }

What will the code print?

  • (A)
    00,11,abc,11,22,acb,22,00,01,11,bac,11,22,bca,22,10,02,11,cba,11,22,cab,22,20,
  • (B)
    00,12,abc,21,11,acb,11,00,01,12,bac,21,11,bca,11,10,02,12,cba,21,11,cab,11,20,
  • (C)
    00,01,abc,10,12,acb,21,00,01,01,bac,10,12,bca,21,10,02,01,cba,10,12,cab,21,20,
  • (D)
    00,11,abc,11,12,acb,21,00,01,11,bac,11,12,bca,21,10,02,11,cba,11,12,cab,21,20,
  • (E)
    00,11,abc,11,12,acb,21,00,10,11,bac,11,12,bca,21,01,20,11,cba,11,12,cab,21,02,

標準解析

AI 生成