关于c:获取数组的全排列

49次阅读

共计 1312 个字符,预计需要花费 4 分钟才能阅读完成。

依据给定的 int 型数组,给出全排列

比方:
[1,2] => [[1,2],[2,1]
[1,2,3] =>[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

#include <stdio.h>
#include <stdlib.h>


int *concat(int* list, int length, int x) {int *result = (int*)malloc((length + 1) * sizeof(int));
    for (int i = length; i > 0; i--) {result[i] = list[i - 1];
    }
    result[0] = x;
    return result;
}

int getFactorial(int n) {
    int total = 1;
    for (int i = 1; i <= n; i++) {total *= i;}
    return total;
}

int** getPermutation(int * list ,int n) {
    int** result;
    int total = getFactorial(n);
    if (n == 2) {result = (int**)malloc(total * sizeof(int*));
        for (int i = 0; i < total; i++) {result[i] = (int*)malloc(n * sizeof(int));
        }
        result[0][0] = list[0];
        result[0][1] = list[1];
        result[1][0] = list[1];
        result[1][1] = list[0];
        return result;
    }else{result = (int**)malloc(total * sizeof(int*));
        for (int i = 0; i < n; i++) {int* tempList = (int*)malloc((n - 1) * sizeof(int));
            int curIdx = 0;
            for (int j = 0; j < n; j++) {if (i == j) continue;
                tempList[curIdx] = list[j];
                curIdx++;
            }
            int** tempResult = getPermutation(tempList, n - 1);
            int tempResultLength = getFactorial(n - 1);
            for (int k = 0; k < tempResultLength; k++) {result[tempResultLength * i + k] = concat(tempResult[k], n - 1, list[i]);    
            }
            free(tempList);
            free(tempResult);
        }
        return result;
    }
}

int main() {
    int n =4;
    int* p = (int*)malloc(n * sizeof(int));
    for (int i = 0; i < n; i++) {p[i] = i + 1;
    }
    
    int **result = getPermutation(p,n);

    for (int i = 0; i < getFactorial(n); i++) {for (int j = 0; j < n; j++) {printf("%d,", result[i][j]);
        }
        printf("\n");
    }

    free(p);
    free(result);

    return 0;
}

正文完
 0