贪心算法

  1. 输入两个整数m和n,从数列1,2,3...n中随意取几个数,使其和等于m,要求将所有可能组合列出来。
  2. 已知有10分、5分和1分硬币无限个,要求把所有和为n分的组合列出来。

1、思路:

  定义函数F(n,m)为取n个数和为m的策略有两种选择,分别是F(n-1,m)和F(n-1,m-n)。

 1 #include <iostream>
 2 #include <vector>
 3 
 4 using namespace std;
 5 
 6 template <typename T>
 7 void PrintVector(vector<T>& vec)
 8 {
 9     for (vector<T>::iterator iter = vec.begin(); iter != vec.end(); iter++)
10         cout << *iter;
11     cout << endl;
12 }
13 
14 void SumComb(int n, int sum, vector<int>& result)
15 {
16     if (sum <= 0)
17     {
18         if (sum < 0) return;
19         PrintVector(result);
20     }
21     else
22     {
23         if (n == 0) return;
24         result.push_back(n);
25         SumComb(n - 1, sum - n, result);
26         result.pop_back();
27         SumComb(n - 1, sum, result);
28     }
29 }
30 
31 int main()
32 {
33     vector<int> result;
34     SumComb(10, 9, result);
35 }

 

2、思路:

 1 void SumCoin(int c, int n, vector<int>& result)
 2 {
 3     if (n <= 0)
 4     {
 5         if (n < 0) return;
 6         PrintVector(result);
 7     }
 8     else
 9     {
10         if (c >= 10)
11         {
12             result.push_back(10);
13             SumCoin(10, n - 10, result);
14             result.pop_back();
15         }
16         if (c >= 5)
17         {
18             result.push_back(5);
19             SumCoin(5, n - 5, result);
20             result.pop_back();
21         }
22         if (c >= 1)
23         {
24             result.push_back(1);
25             SumCoin(1, n - 1, result);
26             result.pop_back();
27         }
28     }
29 }
30 int main()
31 {
32     vector<int> result;
33     SumCoin(10, 23, result);
34 }

 

  

posted on 2013-05-26 21:40  月moon鸟  阅读(142)  评论(0编辑  收藏  举报

导航