回溯法做排列组合,n值大时没有输出
我在用二叉树的回溯法做排列组合,递归左节点和右节点。
之后对n<6的时候做成功了,但是当n>6的时候,程序没有输出
当时我想是不是溢出了,但是我检查了下代码,没有对他原来所需内存进行分配(都没有数字)
#include<stdio.h>
#include<stdlib.h>
struct BiTNode{
int *num;
struct BiTNode *lchild,*rchild,*parent;
};
typedef struct BiTNode tree;
int lengthf(int a1[])
{
int len=0;
while (a1[len++]!='\0');
len--;
return len;
}
int *copy(int a1[],int a2[],int len){
}
tree RCreatetree(tree *T,int i,int n){
tree LCreatetree(tree *T,int i,int n);
int lenp,len,j; //注意这里的i是参数,而不是迭代数,j是迭代数!
struct BiTNode *T1,*T2;
T1=T->rchild;
T1=(struct BiTNode*)malloc(sizeof(struct BiTNode));
T1->parent=T;
T2=T->rchild;
T2=(struct BiTNode*)malloc(sizeof(struct BiTNode));
T2->parent=T;
lenp=lengthf(T->parent->num);
//len=lengthf(T->num);
//printf("长度为%d\n",lenp);
if (i<n){
//printf("1");
T->num =(int *)malloc(sizeof(int) * (lenp+1));
for(j=0; j<lenp; j++){
T->num[j]=T->parent->num[j];
//printf("输入值为%d\n",T->parent->num[j]);
}
T->num[lenp]=i;
T->num[lenp+1]='\0';
//printf("二次输入值为%d\n",T->num[lenp]);
len=lengthf(T->num);
//printf("新建数组的长度为%d\n",len);
i++;
RCreatetree(T1,i,n);
LCreatetree(T2,i,n);
}
else{
T->num =(int *)malloc(sizeof(int) * (lenp+1));
for(j=0; j<lenp; j++){
T->num[j]=T->parent->num[j];
//printf("输入值为%d\n",T->parent->num[j]);
}
T->num[lenp]=i;
for(j=0;j<(lenp+1);j++){
printf("%d,",T->num[j]);
}
printf("\n");
}
}
tree LCreatetree(tree *T,int i,int n){
int lenp,j;
struct BiTNode *T1,*T2;
T1=T->rchild;
T1=(struct BiTNode*)malloc(sizeof(struct BiTNode));
T1->parent=T;
T2=T->rchild;
T2=(struct BiTNode*)malloc(sizeof(struct BiTNode));
T2->parent=T;
lenp=lengthf(T->parent->num);
if (i<n){
T->num =(int *)malloc(sizeof(int) * (lenp));
for(j=0; j<lenp; j++){
T->num[j]=T->parent->num[j];
}
T->num[lenp]='\0';
i++;
RCreatetree(T1,i,n);
LCreatetree(T2,i,n);
}
else{
T->num =(int *)malloc(sizeof(int) * (lenp));
for(j=0; j<lenp; j++){
T->num[j]=T->parent->num[j];
}
for(j=0;j<lenp;j++){
printf("%d,",T->num[j]);
}
printf("\n");
}
}
int main(){
struct BiTNode *T,*T1,*T2;
int i=1,n,lenp;
printf("请输入排列组合数:\n");
scanf("%d",&n);
//初始化二叉树
T=(struct BiTNode*)malloc(sizeof(struct BiTNode));
T->num =(int *)malloc(sizeof(int) * (2));
//T->num[0]=0;
T->num[0]='\0';
T1=T->rchild;
T1=(struct BiTNode*)malloc(sizeof(struct BiTNode));
T1->parent=T;
T2=T->rchild;
T2=(struct BiTNode*)malloc(sizeof(struct BiTNode));
T2->parent=T;
printf("所有的可能组合为:");
RCreatetree(T1,i,n);
LCreatetree(T2,i,n);
}