【发布时间】:2015-10-26 07:08:02
【问题描述】:
例如,总金额应该是5,我有1和2的硬币。那么有3种组合方式:
1 1 1 1 1
1 1 1 2
1 2 2
我看过一些关于如何使用动态编程或递归计算组合总数的帖子,但我想像上面的示例一样输出所有组合。我在下面提出了一个递归解决方案。
它基本上是一种回溯算法,我先从最小的硬币开始,然后尝试得到总金额,然后取出一些硬币并尝试使用第二小的硬币......你可以在下面运行我的代码 http://cpp.sh/
在我的代码中,总金额是 10,可用硬币值是 1、2、5。
#include <iostream>
#include <stdlib.h>
#include <iomanip>
#include <cmath>
#include <vector>
using namespace std;
vector<vector<int>> res;
vector<int> values;
int total = 0;
void helper(vector<int>& curCoins, int current, int i){
int old = current;
if(i==values.size())
return;
int val = values[i];
while(current<total){
current += val;
curCoins.push_back(val);
}
if(current==total){
res.push_back(curCoins);
}
while (current>old) {
current -= val;
curCoins.pop_back();
if (current>=0) {
helper(curCoins, current, i+1);
}
}
}
int main(int argc, const char * argv[]) {
total = 10;
values = {1,2,5};
vector<int> chosenCoins;
helper(chosenCoins, 0, 0);
cout<<"number of combinations: "<<res.size()<<endl;
for (int i=0; i<res.size(); i++) {
for (int j=0; j<res[i].size(); j++) {
if(j!=0)
cout<<" ";
cout<<res[i][j];
}
cout<<endl;
}
return 0;
}
有没有更好的解决方案来输出这个问题的所有组合?动态规划?
编辑:
我的问题是这个问题可以使用动态编程解决吗?
感谢您的帮助。我在这里实现了 DP 版本:Coin Change DP Algorithm Print All Combinations
【问题讨论】:
-
我不认为使用动态编程技术进行详尽的搜索会运行得更快..
-
您有什么问题要解决,还是只是codereview?
-
您没有在简短示例中显示唯一的 5,这是给出 5 总和的合法方式。
-
@n.m.哦,你是对的,我只是改变了那个
-
@softwarenewbie7331 问题是我不知道如何用 DP 解决它,因为我需要打印所有组合...