我們如何列出加起來爲y的x個數字的所有組合?這些數字必須大於0.C++列出加起來爲y的x個數量(必須大於0)的所有組合?
注意:不接受0。我們只能添加x個總和爲y的正數。
實施例#1:
Enter x:
3
Enter y:
5
// x | y
0> 3 + 1 + 1 = 5
1> 2 + 2 + 1 = 5
Count = 2
Done!
實施例#2:對輸入和輸出
#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;
};
實例
Enter x:
2
Enter y:
5
// x | y
0> 3 + 2 = 5
1> 4 + 1 = 5
Count = 2
Done!
x是2。這意味着,我們的函數只可能生成兩個正數,合計爲y,即爲5.
@RobertWish:您可以通過[ 「整數」]的意思是什麼(https://en.wikipedia.org /維基/ Whole_number)?我想你的意思是隻有非負數的整數或自然數。另外,你有嘗試過什麼嗎?至少有一個簡單的方法會導致運行時間很長,但會打印所有的元組。 – Zeta
@Zeta呃,對不起。是的,我的意思是隻有正數。 –
@ Zeta。我立場糾正。我並不是指整數。我的意思是任何大於0的數字!抱歉。 –