2013-03-31 16 views
-1

我們如何列出加起來爲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.

+1

@RobertWish:您可以通過[ 「整數」]的意思是什麼(https://en.wikipedia.org /維基/ Whole_number)?我想你的意思是隻有非負數的整數或自然數。另外,你有嘗試過什麼嗎?至少有一個簡單的方法會導致運行時間很長,但會打印所有的元組。 – Zeta

+0

@Zeta呃,對不起。是的,我的意思是隻有正數。 –

+0

@ Zeta。我立場糾正。我並不是指整數。我的意思是任何大於0的數字!抱歉。 –

回答

1

編輯:對OPs問題不清楚的人。他希望找出寫一些正整數n的方法的數量,作爲k固定的k個正整數之和。

你需要在這裏做一些閱讀和研究你自己的東西,這樣你才能爲我們提供一些你自己的想法。我建議你閱讀了關於...

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

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

+0

有趣的是,我打算要求一個鏈接到一個算法,這個算法與我在這裏要做的事情很接近。謝謝。 –

+1

作爲一個方面說明。尤拉項目(http://projecteuler.net/)包含了很多像這樣的問題,所以如果你要做這樣的幾個,你可能想看看那裏。這些問題會增加難度,以至於當您遇到類似於您所問的問題時,您之前會使用分區和記憶,以便更熟悉它們。 –

相關問題