Für einen Campingausflug kann der Rucksack höchstens limit Kilo tragen. items[i] wiegt weights[i] Kilo. Geh sie der Reihe nach durch: Passt es noch, pack es ein; würde es zu schwer, lass es aus. Schreib pack(items, weights, limit), das zurückgibt, was eingepackt wurde.
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++) {
// dein Code hier: passt das hier noch unter limit, steck es in bag und zähl es zu total dazu
}
return bag;
}
Ausführen testet die Beispiele. Wenn sie passen, drück auf Abgeben.