简体   繁体   中英

How could I solve this recursion problem with C++

Calculate C (n, k) being:

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.

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 (n >= 0) {
    return 1;
  }

is already wrong because there is no such a condition used in the if statement described in the assignment.

Also the condition in this if statement

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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