这是生成字母字符串排列
的源代码的示例输入输出Input:
1
3 8
Output:
Case 1:
ABC
ACB
BAC
BCA
CBA
CAB
我需要在第5行获得CAB
,在此输出的第6行获得CBA
,但我不知道该怎么做。
这是我到目前为止所做的:
#include <stdio.h>
int N, M, count;
char array[27];
void swap (char array[], int i, int j) {
char t;
t = array[i];
array[i] = array[j];
array[j] = t;
}
void perm (char array[], int n, int i) {
if(count == M)return;
int j;
if (i == n) {
for (j=0; j<n; j++) printf ("%c", array[j]);
count++;
printf ("\n");
return;
} else
for (j=i; j<n; j++) {
swap (array, i, j);
perm (array, n, i+1);
swap (array, i, j);
}
}
int main () {
int v[27], i, testCase, T;
int tmp;
char tmpC;
scanf("%d", &T);
for(testCase = 1; testCase <= T; testCase++){
scanf("%d %d", &N, &M);
for (i=0; i<N; i++){
v[i] = i+1;
tmp = i+65;
tmpC = tmp;
array[i] = tmpC;
}
printf("Case %d:\n", testCase);
count = 0;
perm (array, N, 0);
}
return 0;
}
答案 0 :(得分:0)
这里是获取预期输出的更新代码。
#include<stdio.h>
#include<iostream>
using namespace std;
int N, A[27], used[27], M;
string temp;
int counter;
void print()
{
int i;
for (i = 0; i < N; i++)
printf("%c", temp[i]);
printf("\n");
}
void solve(int i, int used[], string str)
{
if (counter == M) return;
if (i == N) {
print();
counter++;
return;
}
for (int k = 0; k < N; k++){
if (!used[k]){
temp = str;
temp += (char)(k + 'A');
used[k] = 1;
solve(i + 1, used, temp);
used[k] = 0;
}
}
}
int main()
{
int T;
scanf("%d", &T);
for (int testCase = 1; testCase <= T; testCase++){
scanf("%d %d", &N, &M);
for (int i = 0; i < N; i++)
used[i] = 0;
counter = 0;
printf("Case %d:\n", testCase);
solve(0, used, "");
}
return 0;
}