Created
March 16, 2012 09:47
-
-
Save edwardbadboy/2049312 to your computer and use it in GitHub Desktop.
none recursive combination generation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//回溯法求组合C(n,k),visit是函数指针,每求出一个组合,就调用一次visit,你可以自己定义一个符合visit签名的函数,并在里面执行需要的动作,然后把地址传给combination | |
int combination(int n,int k,void (*visit)(int* ,int)){ | |
int* d=(int*)malloc(sizeof(int)*k); //一共要选k个东西,就要选k次,d[i]表示选第i次的时候,选的是第几个东西 | |
int count=0; | |
int i; | |
if(d==NULL){ | |
return 0; | |
} | |
i=0; | |
d[i]=0; | |
while(i>=0){ | |
i++;//进入新的一层 | |
if(i<k){ | |
d[i]=d[i-1]+1; | |
}else{//i>=k的情况,应该先输出一个有效的组合,再回溯 | |
count++; | |
visit(d,k);//输出 | |
//回溯 | |
while(i>=0 && (i>=k || d[i]>=n-k+i)){ //由于c和c++语言在判定出i>=0并且i<k后才会去判定d[i],所以i不会越界 | |
i--; | |
} | |
if(i>=0){ | |
d[i]++; | |
} | |
} | |
} | |
free(d); | |
return count; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment