c - 保存所有排列

标签 c

我想编写一个函数来生成数字的所有排列并将它们存储到二维数组中。我知道如何使用递归方法打印出给定数字的所有排列,但我不知道如何将每个排列保存到数组中。

void permute(int *arr, int left, int right, int **per, int rows)
{
int k = 0, j;

if(left == right)
{
    for(j = 0; j <= right; j++)
        printf("%d ", arr[j]);
    printf("\n");
    /*(for(j = 0; j <= right; j++)
    {
        per[k][j] = arr[j];
        k++;
        if(k == rows)
        eturn;
    }*/
}
for(j = left; j <= right; j++)
{
    swap(arr + left, arr + j);
    permute(arr, left + 1, right, per, rows);
    swap(arr + left, arr + j);
}
}

int main(void)
{
int a[3], i, j, **b;

for(i = 0; i < 3; i++)
    a[i] = i;
b = malloc(4 * sizeof(int *));
for(i = 0; i < 4; i++)
    b[i] = malloc(3 * sizeof(int));
permute(a, 0, 2, b, 4);
for(i = 0; i < 4; i++)
{
    printf("\n");
    for(j = 0; j < 3; j++)
        printf("%d ", b[i][j]);
}
printf("\n");
return 0;

}

例如,这段代码将打印出 0123 的排列。我希望 b(2D 数组) 保存前 4 个生成的排列。我的意思是 0123 的排列是:

0 1 2 |
0 2 1 |
1 0 2 |
1 2 0 |
2 1 0 |
2 0 1

b(二维数组)有:

2 0 1 |
0 0 0 |
0 0 0 |
0 0 0 |

最佳答案

首先,看看您的 permute() 函数:

void permute(int *arr, int left, int right, int **per, int rows)

前三个参数对于跟踪排列本身是必需的。最后两个参数是存储排列的数组以及该数组中的行数。缺少的是另一个 int ,它告诉函数已经填充了多少行,所以让我们添加:

void permute(int *arr, int left, int right, int **per, int rows, int rows_filled)

main()中,您只需调用permute(a, 0, 2, b, 4, 0)。在 permute() 本身中,您现在知道必须将结果写入数组中的位置:

if(rows_filled < rows) {
  for(j = 0; j <= right; j++)
    per[rows_filled][j] = arr[j];
  rows_filled++;
}

关于c - 保存所有排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41380479/

相关文章:

c - 如何使用 fwrite 将指针数组的内容写入文件?

C DLL 和新数据服务进程之间基于云的 IPC

c++ - C/C++ : Float comparison speed

c - c语言的套接字编程

c - 链接列表和 fscanf

c++ - 使用指针而不是引用时出现段错误访问指向结构的指针数组

c - C 程序中整数的奇怪行为

c - 为什么 root 的值在 main 函数中打印为 0?

c - 在C中将字符串拆分为数组

c - 为什么在结构和套接字创建中提到套接字的地址族?