【code】全排列

全排列递归算法(DFS)

#include<stdio.h>
#include<malloc.h>
void perm(int* list, int k, int n);
void swap(int* x, int* y);
void show(int* list, int n);
int main() {
	int* list = (int*)malloc(3 * sizeof(int));
	list[0] = 1;
	list[1] = 2;
	list[2] = 3;
	perm(list, 0, 3);
	return 0;
}
/*
 * Function:对k个元素全排列
 * Input:list(全排列内容数组),k(交换第k个数字),n(全排列内容总个数)
 * Return:void
 */
void perm(int* list, int k, int n) {
	if (k == n - 1) {
		show(list, n);
		return;
	}
	for (int i = k; i < n; i++) {
		swap(&list[k], &list[i]);
		perm(list, k + 1, n);
		swap(&list[k], &list[i]);
	}
}

/*
 * Function:交换变量值
 * Input:x(交换元素),y(交换元素)
 * Return:void
 */
void swap(int* x, int* y) {
	int temp = 0;
	temp = *x;
	*x = *y;
	*y = temp;
}

/*
 * Function:遍历输出动态数组
 * Input:list(全排列内容数组),n(全排列内容总个数)
 * Return:void
 */
void show(int* list, int n) {
	for (int i = 0; i < n; i++) {
		printf("%d ", list[i]);
	}
	putchar('\n');
}
发布了46 篇原创文章 · 获赞 13 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/zzy296753977/article/details/101319849