建议了解一下bin packing problem,可能就会更明白我们在干什么了。
大开眼界
vector<int> items = {3, 4, 6, 3, 7, 9, 45, 2, 10}; vector<bool> isSelect(9); vector<int> selected(9); int cap = 45; int selectedMax = 0; void divide(int depth) { if (depth == items.size()) { int sum = 0; for (int i = 0; i < depth; i++) { if (isSelect[i]) { sum += items[i]; } } if (sum <= cap && sum > selectedMax) { selected.clear(); for (int i = 0; i < depth; i++) { if (isSelect[i]) { selected.push_back(items[i]); } } selectedMax = sum; } } else { isSelect[depth] = false; divide(depth+1); isSelect[depth] = true; divide(depth+1); } } int main(void) { int count = 0; while (true) { count++; divide(0); 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; } selectedMax = 0; isSelect.clear(); isSelect.resize(items.size()); selected.clear(); selected.resize(items.size()); } return 0; }