恩恩,明白了,多谢哦
vector<int> items = {5, 4, 3, 2, 2, 2, 2}; vector<bool> isSelect(7); vector<int> selected(7); int knap(int cap) { int remain = 0; int min = cap; for (int i = 0; i < items.size(); i++) { if (!isSelect[i]) { remain = cap - items[i]; if (remain >= 0) { isSelect[i] = true; int t = knap(remain); if (t < min) { selected.clear(); for (int j = 0; j < items.size(); j++) { if (isSelect[j]) { selected.push_back(items[j]); } } min = t; } } isSelect[i] = false; } } return min; } int main(void) { int count = 0; while (true) { count++; knap(10); for (int i = 0; i < selected.size(); i++) { for (int j = 0; j < items.size(); j++) { if (items[j] == selected[i]) { items.erase(items.begin()+j); } } } if (items.size() == 0) { break; } isSelect.clear(); isSelect.resize(items.size()); selected.clear(); selected.resize(items.size()); } return 0; }