Kodewick
開始學 →
小挑戰←→0 / 86

收拾背包

#027小挑戰total + weights[i] <= limit約 7 分鐘

去露營,背包最多背 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)
main.cpp
#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;
}
Ctrl + Enter 也能執行
結果

寫好了先點「執行」試試示例,沒問題再點「提交」。