当前位置:   article > 正文

C++ 子集合枚举

C++ 子集合枚举

给定一个正整数数组 nums[], 求所有可能的组合,使得组合中的元素和等于target, 例如: nums 为 {3, 4, 5},  target 为 9,  解为 {3, 3, 3}, {4, 5}

  1. #include <algorithm>
  2. #include <memory>
  3. #include <string>
  4. #include <vector>
  5. #include <iostream>
  6. #include <set>
  7. #include <stack>
  8. void backtrack(std::vector<int> &state, std::vector<int> &choices, int target, int total, int start, std::vector<std::vector<int>> &res)
  9. {
  10. if (total == target)
  11. {
  12. res.push_back(state);
  13. return;
  14. }
  15. for (int i = start; i < choices.size(); i++)
  16. {
  17. int choice = choices[i];
  18. if (total + choice <= target)
  19. {
  20. total += choice;
  21. state.push_back(choice);
  22. backtrack(state, choices, target, total, i, res);
  23. total -= choice;
  24. state.pop_back();
  25. }
  26. }
  27. }
  28. int main()
  29. {
  30. std::vector<int> choices = {3, 4, 5}; //set
  31. std::vector<int> state{}; //subset
  32. std::vector<std::vector<int>> res{}; //result
  33. int target = 9;
  34. int total = 0;
  35. int start = 0;
  36. backtrack(state, choices, target, total, start, res);
  37. for (auto vv : res)
  38. {
  39. for (auto v : vv)
  40. {
  41. std::cout << v << " ";
  42. }
  43. std::cout << "\n";
  44. }
  45. return 0;
  46. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/从前慢现在也慢/article/detail/756360
推荐阅读
相关标签
  

闽ICP备14008679号