通过使用递归确定两个数组是否相互置换

我在编写一个代码时遇到了一些困难,该代码通过使用递归来确定两个未排序的数组是否是彼此的排列。 我知道如何通过非递归代码确定它,使用排序 – 但我不知道如何通过使用递归来做到这一点。

到目前为止,我无法得到任何真正的想法……

int CheckPermutation(int arr1[], int arr2[], int size) { if (size == 0) return 1; if (size == 1) return (arr1[0] > arr2[0]); } 

这就是我所尝试的,我发现很难从那一点继续

这是一个用于比较2个未排序数组而不修改使用递归的实现的实现:

 #include  // count occurrences of value in an array using recursion int rcount(int value, const int *a, int size) { return size == 0 ? 0 : (value == *a) + rcount(value, a + 1, size - 1); } // check if all entries in a have the same number of occurrences in a and b int check_perm(const int *a, const int *b, int size) { for (int i = 0; i < size; i++) { if (rcount(a[i], a, size) != rcount(a[i], b, size)) return 0; } return 1; } int main(void) { int a[] = { 1, 2, 3, 3, 4, 4, 4, 5, 6, }; int b[] = { 1, 3, 2, 4, 5, 4, 4, 6, 3, }; int c[] = { 1, 3, 2, 4, 5, 4, 4, 6, 6, }; if (check_perm(a, b, sizeof(a) / sizeof(*a))) printf("arrays a and b match\n"); if (!check_perm(a, c, sizeof(a) / sizeof(*a))) printf("arrays a and c do not match\n"); if (!check_perm(b, c, sizeof(b) / sizeof(*b))) printf("arrays b and c do not match\n"); return 0; } 

编辑:

这是一个具有单个递归函数的解决方案。 两个arrays都可能被修改。 如果check_perm()确实返回非零,则两个数组都将被排序:

 int check_perm(const int *a, const int *b, int size) { if (size > 1) { for (int i = 1; i < size; i++) { if (a[0] > a[i]) { int temp = a[0]; a[0] = a[i]; a[i] = temp; } if (b[0] > b[i]) { int temp = b[0]; b[0] = b[i]; b[i] = temp; } } return (a[0] == b[0]) && check_perm(a + 1, b + 1, size - 1); } return 1; }