NYOJ-组合数

#include <stdio.h>
#include <malloc.h>
int main()
{
    int *shu=NULL,n,r,i,j,count=0;
    int flag[10];
    scanf("%d%d", &n,&r);
    if(n==r)
    {

        while(n)
        {
            printf("%d",n);
            n--;
        }
        putchar('\n');
    }
    else
    {
        shu=(int *)malloc((r+1)*sizeof(int));
        for(i=r; i>=1; i--)
            shu[i]=n--;
        for(i=1; i<=r; i++)
            flag[i]=0;
        for(i=r; i>=1; i--)
            printf("%d", shu[i]);
        putchar('\n');
        j=1;
        while(1)
        {
            while(j<r&&shu[j]==j)
            {
                flag[j]=1; /*标记*/
                j++;
                shu[j]--;
                for(i=j; i>=2; i--)
                    shu[i-1]=shu[i]-1;
                for(i=r; i>=1; i--)
                    printf("%d", shu[i]);
                putchar('\n');
            }
            if(shu[j]==j)
                flag[j]=1;
            for(i=1,count=0; i<=r; i++)
                if(flag[i]==1)
                    count++;
            if(count==r) break;
            j=1;
            shu[j]--;
            for(i=r; i>=1; i--)
                printf("%d", shu[i]);
            putchar('\n');
        }
    }
    return 1;
}
View Code

用递归解的

#include<stdio.h>
int n,m;
int num[100];

int dfs(int top, int v)
{
    int i;
    if (v == 0) {
        for(i=m; i>0; i--)
            printf("%d", num[i]);
        printf("\n");
        return 0;
    }
    for(i=top; i>=v; i--) {
        num[v] = i;
        dfs(i-1, v-1);
    }
}

int main()
{
    while(~scanf("%d%d", &n, &m)) {
        dfs(n, m);
    }
    return 0;
}         
View Code

 

posted @ 2014-02-20 22:51  心中的阿哲  阅读(177)  评论(0编辑  收藏  举报