简体   繁体   English

我怎样才能用 C++ 解决这个递归问题

[英]How could I solve this recursion problem with C++

Calculate C (n, k) being:计算 C (n, k) 为:

C (n, 0) = C (n, n) = 1                          if n >= 0
C (n, k) = C (n -1, k) + C (n - 1, k - 1)        if n > k > 0

I really don't understand very well, I know it is a recursive function that got as arguments n and k variables.我真的不太明白,我知道这是一个递归函数,它作为参数nk变量。

This is some of what I'd.这是我想要的一些东西。

#include <iostream>

using namespace std;

int calc(int n, int k) {
  if (n >= 0) {
    return 1;
  }

  if (n > k > 0) {
    return calc(n - 1, k) + calc(n - 1, k - 1);
  }

  return calc(n, k);
}

int main() {
  int n, k;

  cout << "Give a number for n: ";
  cin >> n;

  cout << "Give a number for k: ";
  cin >> k;

  cout << calc(n, k);

  return 0;
}

The first if statement in your function函数中的第一个 if 语句

  if (n >= 0) {
    return 1;
  }

is already wrong because there is no such a condition used in the if statement described in the assignment.已经是错误的,因为在赋值中描述的 if 语句中没有使用这样的条件。

Also the condition in this if statement也是这个 if 语句中的条件

if (n > k > 0)

does not make sense.没有意义。

It seems what you need is the following function definition.看来您需要的是以下函数定义。

#include <iostream>

unsigned long long calc( unsigned int n, unsigned int k )
{
    return k == 0 || not( k < n ) ? 1 : calc( n - 1, k ) + calc( n - 1, k - 1 );
}

int main() 
{
    const unsigned int N = 10;
    
    for ( unsigned int k = 1; k < N; k++ )
    {
        std::cout << calc( N, k ) << '\n';
    }       
}   

The program output is程序输出是

10
45
120
210
252
210
120
45
10

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM