尋找和爲定值的多個數

題目:輸入兩個整數 n 和 m,從數列1,2,3…n 中 隨意取幾個數,使其和等於 m ,要求將其中所有的可能組合列出來。

code:

 1 #include<list>  
 2 #include<iostream>  
 3 using namespace std;  
 4   
 5 list<int>list1;  
 6 void find_factor(int sum, int n)   
 7 {  
 8     // 遞歸出口  
 9     if(n <= 0 || sum <= 0)  
10         return;  
11       
12     // 輸出找到的結果  
13     if(sum == n)  
14     {  
15         // 反轉list  
16         list1.reverse();  
17         for(list<int>::iterator iter = list1.begin(); iter != list1.end(); iter++)  
18             cout << *iter << " + ";  
19         cout << n << endl;  
20         list1.reverse();      
21     }  
22       
23     list1.push_front(n);      //典型的01揹包問題  
24     find_factor(sum-n, n-1);   //放n,n-1個數填滿sum-n  
25     list1.pop_front();  
26     find_factor(sum, n-1);     //不放n,n-1個數填滿sum   
27 }  
28   
29 int main()  
30 {  
31     int sum, n;  
32     cout << "請輸入你要等於多少的數值sum:" << endl;  
33     cin >> sum;  
34     cout << "請輸入你要從1.....n數列中取值的n:" << endl;  
35     cin >> n;  
36     cout << "所有可能的序列,如下:" << endl;  
37     find_factor(sum,n);  
38     return 0;  
39 }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章