Instantly share code, notes, and snippets.

Embed
What would you like to do?
递归回溯法生成数字排列。
#include <stdio.h>
int visit[1024] = {0};
void perm_rec(int *a, int n, int i)
{
int j;
if (i == n) {
for (j = 0; j < n; j++)
printf("%d ", a[j]);
printf("\n");
return;
}
for (j = 0; j < n; j++) {
if (visit[j] == 0) {
visit[j] = 1;
a[i] = j;
perm_rec(a, n, i + 1);
visit[j] = 0;
}
}
}
void permutation(int *a, int n)
{
int i;
for (i = 0; i < n; i++)
visit[i] = 0;
perm_rec(a, n, 0);
}
int main()
{
int a[5];
permutation(a, 5);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment