求n个数(1,2,...,n)中k个数的组

来源:互联网 发布:怎么养才能加入淘宝网 编辑:程序博客网 时间:2024/06/05 04:59

网上的程序,终于没有采用递归,对其的几点说明:这逻辑。。。

1.程序是通过push 函数中当前top的位置来判断是否满足k个数,如果当前top的位置为k-1,则返回1,否则,返回0;

2.程序中如何改变数值呢?在pop的时候指针保存了当前要pop出去的值,然后再top-1。这样下次直接--,然后重新入栈即可。

3.在第k个数的所有情况已经输出后,如何对第k-1个数,开始进行修改,进而组合呢?当程序输出一个序列后,随机将该第k个数出栈,保存值,并且此时top-1,当程序判断出temp==1,即表示,应该再回退一个(即在此出栈),出栈时保存了第k-1个数的值,并且指针(top-1)-1,这样可在此入栈,top指向第k-1个数。

 

#include <stdlib.h>
int pop(int *);
int push(int );
void combination(int ,int );
int stack[3]={0};
int top=-1;
int main()
{
int n,m;
printf("Input two numbers:\n");
scanf("%d%d",&n,&m);
combination(n,m);
system("pause");
printf("\n");
}
void combination(int m,int n)
{
 int temp=m;
 push(temp);
 while(1)
 {
  if(1==temp) // 当输出XY1的排序后,先将1出栈,这里在此出栈,使能对1的前一个数据Y修改。
  {
   if(pop(&temp)&&stack[0]==n) //当栈底元素弹出&&为可能取的最小值,循环退出
    break;
  }
  else if( push(--temp))
  {
   printf("%d%d%d ",stack[0],stack[1],stack[2]);
   pop(&temp);
  }
 }
}
int push(int i)
{
 stack[++top]=i;
 if(top<2)  // 保证是求n个数中的3个数,这地方写死了。后续要改。
  return 0;
 else
  return 1;
}
int pop(int *i)
{
 *i=stack[top--];  // 保存当前要出栈的数值
 if(top>=0)
  return 0;
 else
  return 1;
}