2013-10-29 实验之数组中元素全排列(递归思想题)

来源:互联网 发布:什么时候开始有的网络 编辑:程序博客网 时间:2024/05/19 19:59

实验描述:数组中元素全排列

注意事项:注意递归无出口,递归到最后一个自动返回,深度最后一层处理数组

应用程序:

#include<stdlib.h>#include<stdio.h>void execCombination(int *combArray, int index, int num, int depth){int i;int swap;for(i = index; i < num; i++){swap = combArray[index]; //swap each elementcombArray[index] = combArray[i];combArray[i] = swap;execCombination(combArray, index+1,  num, depth+1);combArray[i] = combArray[index]; //restore the previous stationcombArray[index] = swap;}if(depth == num){int j;//save the array and do your logical codefor(j=0; j < num; j++){printf("%-4d ", combArray[j] );}printf("\n");}}int main(void){int num;printf("Please enter the length:");scanf("%d", &num);int *combArray = (int *)malloc(sizeof( int ) * num);int i;for(i=0; i < num;i++){combArray[i] = i+1;}execCombination(combArray, 0, num, 1);return 0;}