#include #include class Solution { public: static std::vector> combinationSum(const std::vector& candidates, int target, int prev = 0) { std::vector> ret; for (int v : candidates) { if (v >= prev && target - v >= v) { std::vector> t = combinationSum(candidates, target - v, v); for (std::vector& i : t) { i.push_back(v); } ret.reserve(ret.size() + t.size()); ret.insert(ret.end(), t.begin(), t.end()); } else if (v == target) { ret.emplace_back(1, v); } } return ret; } }; int main() { auto ret = Solution::combinationSum({2, 3, 5}, 8); for (const auto& i : ret) { for (auto j : i) { std::printf("%d ", j); } std::printf("\n"); } return 0; }