排列组合算法
排列算法程序代码:
#include <stdio.h> #include <string.h> #define NUM 4 #define MAX_DEPTH 2 int mark[NUM+1] = {0}; int printList[NUM+1] = {0}; void dfs(int depth); int main(void) { dfs(1); getchar(); return 0; } void dfs(int depth) { char s[40] = {0}; int i, j, k; for (i = 1; i <= NUM; i++) { if (!mark[i]) { mark[i] = 1; printList[depth] = i; if (depth < MAX_DEPTH) { dfs(depth+1); } else { for (j = 1; j <= MAX_DEPTH; j++) { printf("%d ", printList[j]); } printf("\n"); } mark[i] = 0; } } }
组合算法
程序代码:
#include <stdio.h> #include <string.h> #define N 3 #define M 5 int combination[N+1] = {0}; void recursion(int m, int depth); int main(void) { recursion(1, 1); getchar(); return 0; } void recursion(int m, int depth) { char s[40] = {0}; int i, j, k; for (i = m; i <= M; i++) { combination[depth] = i; if (depth == N) { for (j = 1; j <= N; j++) { printf("%d ", combination[j]); } printf("\n"); } else { recursion(i+1, depth+1); } } }