去露营,背包最多背 limit 公斤。items[i] 重 weights[i] 公斤。按顺序一样一样看:装进去不超重就装,超重就跳过。写 pack(items, weights, limit),返回装进去的东西。
pack({"tent", "stove", "book"}, {5, 3, 1}, 8)→['tent', 'stove']pack({"tent", "stove", "book"}, {5, 4, 1}, 8)→['tent', 'book']vector<string> pack(const vector<string> &items, const vector<int> &weights, int limit)#include <string>
#include <vector>
using namespace std;
vector<string> pack(const vector<string> &items, const vector<int> &weights, int limit) {
vector<string> bag;
int total = 0;
for (int i = 0; i < items.size(); i++) {
// 在这里写:加上这一样不超过 limit,就装进 bag,total 也加上
}
return bag;
}
写好了先点「运行」试试示例,没问题再点「提交」。