编程总结
本篇参考liuyubobo
46. 全排列
思路:DFS
/* 定义当前遍历深度count为全局变量 */
int gCount;
void DFS(int *nums, int numsSize, int depth, int *path, int *visited, int **res)
{
// 递归终止条件,满足 depth == numSize
if (depth == numsSize) {
res[gCount] = (int *)malloc(sizeof(int) * numsSize);
memcpy(res[gCount++], path, sizeof(int) * numsSize);
return;
}
for (int i = 0; i < numsSize; i++) {
// 如果已经遍历了,continue
if (visited[i] == true) {
continue;
}
path[depth] = nums[i];
visited[i] = true;
DFS(nums, numsSize, depth + 1, path, visited, res);
// 如果满足了递归终止条件,会下来,used 需要重新赋值 false
visited[i] = false;
}
}
int **permute(int *nums, int numsSize, int *returnSize, int **returnColumnSizes)
{
(*returnSize) = 1; // 初始值
// 排列数 n!
for (int i = 1; i <= numsSize; i++) {
(*returnSize) *= i;
}
*returnColumnSizes = (int *)malloc(sizeof(int) * (*returnSize));
for (int i = 0; i < (*returnSize); i++) {
(*returnColumnSizes)[i] = numsSize;
}
int **res = (int **)malloc(sizeof(int *) * (*returnSize));
int *path = (int *)malloc(sizeof(int) * numsSize);
int *visited = (int *)malloc(numsSize * sizeof(int));
gCount = 0;
DFS(nums, numsSize, 0, path, visited, res);
return res;
}
int main() {
int **res = (int **)malloc(sizeof(int *) * 3);
int nums[3] = {1, 2, 3};
int numsSize = 3;
int returnSize = 3;
int *returnColumnSizes = (int *)malloc(sizeof(int *));
for (int i = 0; i < 3; i++) {
res[i] = (int *)malloc(sizeof(int) * 3);
}
res = permute(nums, numsSize, &returnSize, &returnColumnSizes);
return 0;
}
全排列的树形结构:
- DFS 下去,找到第一个解
2)满足第一次递归终止条件后,归回来,状态重置