qijixingzhe 2018-03-07 02:11 采纳率: 66.7%
浏览 1690
已采纳

已知7个不同的字母a,b,c,d,e,f,g。从这7个字母中依次选择3个,4个,5个字母。打印出来

已知7个不同的字母a,b,c,d,e,f,g。从这7个字母中选择3个字母全部打印出来,共有35种方案。比如abc,abd,abe......。选择4个打印出来也是35种。选择5个打印出来共有21种比如abcde,abcdf,abcdg。
用c语言或者C++作。我用的是vs2015编译器。只要它能通过编译就行。能不能帮个忙稍微
写一点注释。哈哈。谢谢啦老铁。
我这边编译器老是提示cout,cin,endl没有定义。麻烦把需要导入的包在开头写一下。要不我这里编译无法通过
不要随机数,要全部组合。谢谢啦老铁

  • 写回答

9条回答 默认 最新

  • wallesyoyo 2018-03-07 07:22
    关注
    
    #include <cstdio>
    #include <cstring>
    
    char t[1024] = { 0 };
    void PrintCombination(char* s, int n, int k, int selected = 0, int depth = 0)
    {
        if (selected == k)
        {
            printf("%s ", t);
            return;
        }
    
        if (depth < n)
        {
            t[selected] = s[depth];
            PrintCombination(s, n, k, selected + 1, depth + 1);
            t[selected] = '\0';
            PrintCombination(s, n, k, selected, depth + 1);
        }
    }
    
    int main()
    {
        char* s = "abcdefg";
        int n = strlen(s);
    
        for (int i = 3; i <= 5; ++i)
        {
            printf("[%dC%d]:\n", n, i);
            PrintCombination(s, n, i);
            printf("\n");
        }
    
        return 0;
    }
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(8条)

报告相同问题?