题解 | #最小邮票数#
最小邮票数
https://www.nowcoder.com/practice/83800ae3292b4256b7349ded5f178dd1
#include <bits/stdc++.h> using namespace std; const int N = 20; int v[N]; int m,n,minK; //总值,邮票数量,最小数量 //当前的邮票编号,当前总价值,当前邮票数量 void dfs(int index,int sum,int k){ if(sum == m){ if(k < minK){ minK = k; return; } } if(index >= n or sum > m) return ; //穷举,对任意一张邮票,走遍选择它与不选择它的两种可能。 dfs(index + 1, sum + v[index] , k + 1); dfs(index + 1, sum , k ); } int main(){ while(cin >> m >> n){ //初始化最小数量为邮票总数 minK = n; for(int i = 0 ; i < n ; i ++) cin >> v[i]; dfs(0,0,0); if(minK == n) cout << 0 << endl; else cout << minK << endl; } }
#include <bits/stdc++.h> using namespace std; const int MAXM = 101; const int MAXN = 21; const int Max = 99999; int dp[MAXN][MAXM]; int main() { for (int i = 0; i < MAXN; i++) { for (int j = 0; j < MAXM; j++) { dp[i][j] = Max; } } for (int i = 0; i < MAXN; i++) dp[i][0] = 0; int M, N; cin >> M >> N; int v[N]; for (int i = 0; i < N; i++) cin >> v[i]; for (int i = 1; i <= N; i++) { for (int j = 1; j <= M; j++) { if (v[i - 1] <= j) { dp[i][j] = min(dp[i - 1][j], dp[i - 1][j - v[i - 1]] + 1); } else { dp[i][j] = dp[i - 1][j]; } } } if (dp[N][M] != Max) cout << dp[N][M] << endl; else cout << 0 << endl; return 0; }