您的位置:首页 > 健康 > 美食 > C++ 子集合枚举

C++ 子集合枚举

2025/3/14 7:12:11 来源:https://blog.csdn.net/zg260/article/details/139743962  浏览:    关键词:C++ 子集合枚举

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

#include <algorithm>
#include <memory>
#include <string>
#include <vector>
#include <iostream>
#include <set>
#include <stack>void backtrack(std::vector<int> &state, std::vector<int> &choices, int target, int total, int start, std::vector<std::vector<int>> &res)
{if (total == target){res.push_back(state);return;}for (int i = start; i < choices.size(); i++){int choice = choices[i];if (total + choice <= target){total += choice;state.push_back(choice);backtrack(state, choices, target, total, i, res);total -= choice;state.pop_back();}}
}int main()
{std::vector<int> choices = {3, 4, 5}; //setstd::vector<int> state{}; //subsetstd::vector<std::vector<int>> res{}; //resultint target = 9;int total = 0;int start = 0;backtrack(state, choices, target, total, start, res);for (auto vv : res){for (auto v : vv){std::cout << v << " ";}std::cout << "\n";}return 0;
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com