我如何通过C中的递归置换来更改叶片位置字符串



这是我的源代码的示例输入输出,以生成字母字符串的置换量

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;
}

您的交换功能将无法完成工作。您想要的算法似乎是一种根据其原始顺序的元素更喜欢元素的算法,因此它将始终始终选择A优于C,将第一个可用。交换算法比以前的排列最少的变化更喜欢。

要获得所需的输出,我认为您需要更改为其他算法,该算法会采用一个元素(依次循环在每个元素中);对于每个选择,它都会在列表的其余部分中出现。

这是获得预期输出的更新代码。

#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;
}

最新更新