标签:
问题描述:
有1分,2分,5分,10分四种硬币,每种硬币数量无限,给定target分钱,求有多少种组合可以组合成target分钱?(2012创新工场)
解答:(基于深度优先的递归)
#include <iostream> #include <vector> using namespace std; void dfs(int index, int total, int target, int &count, vector<int> res, vector<vector<int>> &ans, int A[],int n) { if(total>target)return; if(total==target) { // cout<<"count="<<count<<endl; // for (int i=0;i<res.size();i++) // { // cout<<res[i]<<" "; // } // cout<<endl; ans.push_back(res); count++; return; } for (int i=index;i<n;i++) { total+=A[i]; res.push_back(A[i]); dfs(i,total,target,count,res,ans,A,n); res.pop_back(); total-=A[i]; } } int main() { int A[]={1, 2, 5, 10}; int n=sizeof(A)/sizeof(int); int index=0; int total=0; int target=18; int count=0; vector<int> res; vector<vector<int>> ans; dfs(index, total, target, count, res, ans, A, n); cout<<"共有count="<<count<<endl; for (int i=0;i<ans.size();i++) { for (int j=0;j<ans[i].size();j++) { cout<<ans[i][j]<<" "; } cout<<endl; } return 0; }
标签:
原文地址:http://www.cnblogs.com/Vae98Scilence/p/4392304.html