trying to write a recursive function that counts the number of sequences that sum up to that number C++

后端 未结 6 1607
野趣味
野趣味 2021-01-20 02:01

Okay, so here is what I\'m trying to do. The user inputs a number. I\'m trying to write a recursive function that counts the number of sequences that sum up to that number (

6条回答
  •  长发绾君心
    2021-01-20 02:30

    Hint: try to find a function that gives the number of sequences with sum n and terms not larger than k.

    EDIT:
    Forgive me if this sounds harsh, but... your updated code is all wrong. It's hard to see what you intended. I can guess, but that would be pointless.

    Here's what I had in mind: a sequence should be in nonincreasing order, like "2 2 1 1 1 1". So how many such sequences add up to 6? Well, find the number of such sequences starting with 1, then the number of sequences starting with 2, and so on up to 6, and add them up. And how many sequences start with 2 and add up to six? (This is where the recursion comes in.) In each such sequence, the first term is 2 and the rest add up to 4 with no term exceeding 2, so we must find the number of sequences adding up to 4 with no term greater than 2. So write the signature first, then the iteration loop, then the recursive call and you're done.

    EDIT:
    All right, here's everything but the loop:

    int partition(int n, int max)
    {
      if(n==0)
        return(0);
      int ret = 0;
      if(n<=max)
        ret=1;
      for(...)
      {
        ...
      }
      return(ret);
    }
    

    Can you fill in the blanks?

提交回复
热议问题