题目描述:有若干张邮票,要求从中选取最少的邮票张数凑成一个给定的总值。 如,有1分,3分,3分,3分,4分五张邮票,要求凑成10分,则使用3张邮票:3分、3分、4分即可。
//DFS递归剪枝求法
#include "bits/stdc++.h"
using namespace std;
int a[21];
int fsum;
int n;
vector<int> fdepth;
void dfs (int i, int sum, int depth){
if (i > n - 1) return ;
if (sum > fsum) return ;
else if (sum == fsum) {
fdepth.push_back(depth);
// cout << depth << " " <<endl;
return ;
}
else {
dfs(i+1,sum,depth++);
dfs(i+1,sum+a[i+1],depth++);
}
}
bool cmp (const int &a, const int &b){
return a < b;
}
int main(){
while (scanf("%d",&fsum) != EOF){
scanf ("%d", &n);
memset(a,0,sizeof(a));
fdepth.clear();
//将大的留在前面
for (int i = n - 1; i >= 0; i--){
scanf ("%d", &a[i]);
}
for (int i = 0; i < n; i++){
dfs(i,a[i],1);
}
if (!fdepth.empty()){
sort(fdepth.begin(),fdepth.end(),cmp);
printf("%d\n",fdepth[0]);
}
else printf("0\n");
}
}
这题我是用DFS暴力搜索+贪心剪枝做的,居然神奇的AC了。可能是数据量比较少,理论上时间复杂的是O(2^n),基本上是过不了的。所以,在忘记DP的情况下,大胆剪枝暴力,能得一点分得一点分啊哈哈。