列出加起来等于y的x个数(必须大于0)的所有组合

C++ List all combinations of x amount of numbers (must be bigger than 0) that adds up to y?

本文关键字:大于 组合 个数 起来      更新时间:2023-10-16

我们如何列出所有x数量的数字加起来等于y的组合?这些数字必须大于0。

注:不接受0。我们只能把x个正数加起来等于y。

#include <string>
#include <iostream>
// Prototype.
bool Function( unsigned int in_x, unsigned int in_y );
int main() {
    // Declarations.
    unsigned int x = 0;
    unsigned int y = 0;
    // Ask for x.
    std::cout << "nEnter x:n";
    std::cin >> x;
    // Ask for y.
    std::cout << "nEnter y:n";
    std::cin >> y;
    // Begin.
    Function( x, y );
    // Notify and stop.
    std::cout << "nDone!n";
    std::cin.ignore();
    ::getchar();
    // Exit with success.
    return 0;
};
bool Function( unsigned int in_x, unsigned int in_y ) {
    // Error handler.
    if( in_x == 0 ) {
        return false; }
    // Generate and list...
    // *Note: 0 is not accepted. We can only add x amount of positive numbers that adds up to y.
    // How do we do it?
    return false;
};

输入和输出示例:

示例# 1:

Enter x:
3
Enter y:
5
//          x               |   y
0>      3   +   1   +   1   =   5
1>      2   +   2   +   1   =   5
Count = 2
Done!

例2:

Enter x:
2
Enter y:
5
//          x       |   y
0>      3   +   2   =   5
1>      4   +   1   =   5
Count = 2
Done!

x = 2。这意味着,我们的函数只能生成两个正数加起来等于y,也就是5。

编辑:对于OPs问题不清楚的人。他想找出有多少种方法可以把某个正整数n写成k个正整数的和,其中k是固定的。

OP你需要自己做一些阅读和研究,这样你就可以给我们提供一些你自己的想法。我建议你仔细阅读……

分区http://en.wikipedia.org/wiki/Partition_ (number_theory)

和http://en.wikipedia.org/wiki/Memoization