题解 | #称砝码#
称砝码
https://www.nowcoder.com/practice/f9a4c19050fc477e9e27eb75f3bfd49c
#include <iostream> using namespace std; #include <set> #include <vector> int main() { int kind; cin >> kind; vector<int> weight(kind, 0); vector<int> num(kind, 0); for (int i = 0; i < kind; i++) { cin >> weight[i]; } for (int i = 0; i < kind; i++) { cin >> num[i]; } set<int> result; result.insert(0); for (int j = 0; j < weight.size(); j++) { for (int i = 1; i <= num[j]; i++) { set<int> temp(result); for (auto& t : temp) { result.insert(t + weight[j]); } } } cout << result.size() << endl; }
set容器不允许重复元素,每添加一个砝码,都往之前的情况上加,就可以遍历出所有情况了
华为机试刷题记录 文章被收录于专栏
记录一下手打代码的解题思路方便复习