33,010
社区成员
发帖
与我相关
我的任务
分享
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
void func(int N, int table[], int cnt)
{
int i;
if (N <= 0)
{
if (0 == N)
{
for (i = 0; i < cnt - 1; ++i)
{
printf("%d+", table[i]);
}
printf("%d\n", table[cnt - 1]);
}
}
else
{
for (i = N; i >= 1; --i)
{
if (i <= table[cnt - 1])
{
table[cnt] = i;
func(N - i, table, cnt + 1);
}
}
}
}
int main()
{
int n;
int *table;
printf("%s\n", "输入n值大小:");
scanf("%d", &n);
if (NULL == (table = (int *)malloc((n + 1) * sizeof(int))))
{
exit(1);
}
table[0] = n;
func(n, table + 1, 0);
free(table);
system("pause");
return 0;
}
#include<stdio.h>
#include<string.h>
void combination(const char s[],int m,int n)
{
int i;
char t[30];
for(i=n;i>=m;i--)
{
if(!strcmp(s,"")) sprintf(t,"%d",i);
else sprintf(t,"%d+%s",i,s);
combination(t,i,n-i);
}
if(!n) printf("%s\n",s);
}
int main()
{
combination("",1,6);
getchar();
}
#include<stdio.h>
#include<string.h>
void combination(const char s[],int m,int n)
{
int i;
char t[30];
for(i=n;i>=m;i--)
{
sprintf(t,"%d+%s",i,s);
combination(t,i,n-i);
}
if(!n)
{
printf("%s\n",s);
}
}
int main()
{
combination("",1,6);
getchar();
}
procedure TForm1.Button1Click(Sender: TObject);
procedure combination(const s:string; m,n:integer);
var
i: integer;
begin
for i:=n downto m do combination(IntToStr(i)+','+s,i,n-i);
if n=0 then Memo1.Lines.Add(copy(s,1,Length(s)-1));
end;
begin
combination('',1,6);
end;
结果是:
6
3+3
4+2
2+2+2
5+1
3+2+1
4+1+1
2+2+1+1
3+1+1+1
2+1+1+1+1
1+1+1+1+1+1