问题描述:超市有4种包装的鸡蛋,分别是3个一盒,6个一盒,9个一盒和20个一盒。问顾客要买N个鸡蛋时,所有的组合方案。(Morgen Stanley 2014 Intern).
还有找零钱问题要求输出所有方案,也是一个意思。
核心代码:
1 void BuyEggsCore(vector<const int> &coins, const int target, int sum, int i, vector<int> &count, vector<vector<int>> &ret) { 2 if (i >= coins.size()) return; 3 int left_value = target - sum; 4 for (int j = 0; j * coins[i] <= left_value; ++j) { 5 sum = target - left_value + j * coins[i]; 6 count[i] = j; 7 if (sum == target) { 8 ret.push_back(count); 9 } 10 else if (sum < target) { 11 BuyEggsCore(coins, target, sum, i + 1, count, ret); 12 } 13 } 14 } 15 16 vector<vector<int>> BuyEggs(vector<const int> &coins, const int target) { 17 vector<vector<int>> ret; 18 vector<int> count; 19 count.resize(coins.size()); 20 BuyEggsCore(coins, target, 0, 0, count, ret); 21 return ret; 22 }
2014.06.20 update: 这不就是Leetcode上的combination sum嘛...