5.0 数据结构之排列与组合

编程总结

本篇参考liuyubobo

46. 全排列

5.0 数据结构之排列与组合

思路: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;
}

全排列的树形结构:

  1. DFS 下去,找到第一个解
    5.0 数据结构之排列与组合
    2)满足第一次递归终止条件后,归回来,状态重置
上一篇:C语言指针和动静态分配内存


下一篇:《C和指针》学习笔记