编写递归C函数来计算组合 [英] Write a recursive C function to calculate combination

查看:118
本文介绍了编写递归C函数来计算组合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

计算一次取k个n个对象组合的递归定义可以定义如下:

C(n,k)= {1,如果k = 0或n = k

C(n-1,k)+ C(n-1,k-1)如果n> k> 0

}

Writea递归C函数实现上述。



我尝试过:



The recursive definition to caculate the combination of n objects taken k at a time can be defined as follows:
C(n,k) = {1, if k = 0 or n = k
C(n-1, k) + C(n-1, k-1) if n>k>0
}
Writea recursive C function to implement the above.

What I have tried:

#include<iostream>
02
#include<stdlib.h>
03
using namespace std;
04
 
05
void combination(int m , int n , int result[]);
06
void output(int result[]);
07
int taco;
08
 
09
int main(int argc , char** argv)
10
{
11
    int m, n;
12
    int* result;
13
    m = atoi(argv[1]);
14
    taco = n = atoi(argv[2]);
15
    result = (int*)malloc(sizeof(int)*n); //Dynamic array.
16
    //The size of array is same with n.
17
    for(int i = 0 ; i < n ; i++) result[i] = 0;
18
    combination(m , n , result);
19
}
20
 
21
 
22
void combination(int m , int n , int result[])
23
{
24
  //You have to write your algorithm here
25
}
26
void output(int result[]) //You can call output function after you put result in result[].
27
{
28
    cout<<"< ";
29
    for(int i = taco - 1 ; i >=0 ; i--)
30
        cout<<result[i]<<" ";
31
    cout<<">"<<endl;
32
}

推荐答案

只需将完成的问题发布在你必须在这里编写算法不会帮助你:我们不做你的功课:这是有原因的。它就是为了让你思考你被告知的事情,并试着理解它。它也在那里,以便您的导师可以识别您身体虚弱的区域,并将更多的注意力集中在补救措施上。



亲自尝试,你可能会发现它不是和你想的一样困难!



如果遇到具体问题,请询问相关问题,我们会尽力提供帮助。但我们不打算为你做这一切!
Just posting your homework question complete with "You have to write your algorithm here" isn't going to help you: We do not do your homework: it is set for a reason. It is there so that you think about what you have been told, and try to understand it. It is also there so that your tutor can identify areas where you are weak, and focus more attention on remedial action.

Try it yourself, you may find it is not as difficult as you think!

If you meet a specific problem, then please ask about that and we will do our best to help. But we aren't going to do it all for you!


只需将定义放入C函数:

Just put the definition into a C function:
int C(int n, int k)
{
    if (k == 0 || n == k)
        return 1;
    else if (n > k)
        return C(n-1, k) + C(n-1, k-1);
    return 0;
}


这篇关于编写递归C函数来计算组合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆