2018-12-03 14:30

# 关于C语言的一道递归题

`````` #include "stdafx.h"

void combinations(int n,int r,int i)
{
static int n0=n,r0=r;
int i1;
for(i1=i;i1<=n0-r+1;i1++){
printf("%d ",i1);
if(r-1>0)
combinations(n-1,r-1,i1+1);
else printf("\n");
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n,r,i=1;
printf("ENTER N R:");
scanf_s("%d%d",&n,&r);
printf("combinations:\n");
combinations(n,r,i);
return 0;
}
``````
• 点赞
• 写回答
• 关注问题
• 收藏
• 邀请回答

• # 如果问题得到解决，请点我回答左上角的采纳和向上的箭头，谢谢

``````#include "stdlib.h"
#include "string.h"

#define MAX 20

void combinations(char * prefix, int start, int n, int remain)
{
if (remain == 0)
{
printf("%s\n", prefix);
return;
}
for (int i = start; i <= n - remain + 1; i++)
{
char temp[5];
sprintf(temp, "%d ", i);
if (i != start)
memset(prefix, ' ', sizeof(char) * strlen(prefix));
char * acc = (char *)malloc(MAX * sizeof(char));
acc[0] = '\0';
strcat(acc, prefix);
strcat(acc, temp);
combinations(acc, i + 1, n, remain - 1);
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n,r,i=1;
printf("ENTER N R:");
scanf_s("%d%d",&n,&r);
printf("combinations:\n");
char seed[MAX];
seed[0] = '\0';
combinations(seed, 1, n, r);
return 0;
}
``````

vs2013+，需要把sprint、strcat、strlen等换成带 _s的版本，这个你自己去做了。

点赞 评论
• weixin_43938200 2018-12-07 02:08
``````#include "stdafx.h"

void combinations(int n,int r,int i)
{
static int n0=n,r0=r,flag=0;
int i1,j;
for(i1=i;i1<=n0-r+1;i1++){
if(flag==1){
for(j=0;j<r0-r;j++)
printf("  ");
flag=0;
}
printf("%d ",i1);
if(r-1>0)
combinations(n-1,r-1,i1+1);
else{
printf("\n");
flag=1;
}
}
}
int _tmain(int argc, _TCHAR* argv[])
{
int n,r,i=1;
printf("ENTER N R:");
scanf_s("%d%d",&n,&r);
printf("combinations:\n");
combinations(n,r,i);
return 0;
}
``````

贴一个自己的答案以备参考，可能更好理解也可能更难理解

点赞 评论