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

后端 未结 6 1577
野趣味
野趣味 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:42

    Define P(n) as the number of ways to partition n, restricting n to be an integer, n >= 1.

    Define p(n, k) as the number of ways to partition n using numbers no larger than k, restricting k to be an integer, k >= 1, k <= n.

    It follows that P(n) = sum (i: 1..n) p(n, i).

    To find p(n, k), first note that we neatly avoid double-counting by simply keeping the partition sorted: take the largest chunk first. So the first chunk may have any size from 1 up to k, and then the rest of the chunks must account for the rest of the total n, and be no larger than the first chunk.

    Thus p(n, k) = sum (i: 1..k) p(n - i, i).

    As a base case, p(1, 1) = 1.


    A sample implementation, very much not guaranteed to be at all efficient, or even to compile (but it should give you the basic idea) - spoilers!

    // A utility function to represent the result of appending to a vector,
    // as a new vector (without affecting the previous one).
    template 
    vector operator<<(vector copy, T to_append) {
        // We passed by value to get a copy implicitly.
        copy.push_back(to_append);
        return copy;
    }
    
    // A utility function to append one vector to another.
    template 
    vector& operator+=(vector& original, const vector& to_append) {
        // 'copy' is in namespace std:: and defined in .
        // 'back_inserter' is in namespace std:: and defined in .
        copy(to_append.begin(), to_append.end(), back_inserter(original));
        return original;
    }
    
    vector > partitions(int remaining, int limit, vector prefix) {
        // Finds the partitions of some larger number which start with the
        // numbers in 'prefix', such that the rest of the "chunks" sum to
        // 'remaining' and are all no larger than 'limit'.
    
        // 'max' is in namespace std:: and defined in . We restrict
        // the 'limit' to be no more than 'remaining'.
        limit = max(remaining, limit);
    
        vector > result;
    
        // Base case. 
        if (remaining == 1) {
            return result << (prefix << 1); // note the parentheses are required!
        }
    
        for (int i = limit; i > 0; --i) {
            result += partitions(remaining - i, i, prefix << i);
        }
    
        return result;
    }
    

提交回复
热议问题