cpp-algo-cases/chapter_backtracking/subset_sum_i_naive.cpp

55 lines
1.5 KiB
C++
Raw Normal View History

2024-02-20 16:13:23 +08:00
/**
* File: subset_sum_i_naive.cpp
* Created Time: 2023-06-21
* Author: krahets (krahets@163.com)
*/
#include "../utils/common.hpp"
/* <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><E3B7A8><EFBFBD>Ӽ<EFBFBD><D3BC><EFBFBD> I */
void backtrack(vector<int> &state, int target, int total, vector<int> &choices, vector<vector<int>> &res) {
// <20>Ӽ<EFBFBD><D3BC>͵<EFBFBD><CDB5><EFBFBD> target ʱ<><CAB1><EFBFBD><EFBFBD>¼<EFBFBD><C2BC>
if (total == target) {
res.push_back(state);
return;
}
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>
for (size_t i = 0; i < choices.size(); i++) {
// <20><>֦<EFBFBD><D6A6><EFBFBD><EFBFBD><EFBFBD>Ӽ<EFBFBD><D3BC>ͳ<EFBFBD><CDB3><EFBFBD> target <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD><D1A1>
if (total + choices[i] > target) {
continue;
}
// <20><><EFBFBD>ԣ<EFBFBD><D4A3><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD>񣬸<EFBFBD><F1A3ACB8><EFBFBD>Ԫ<EFBFBD>غ<EFBFBD> total
state.push_back(choices[i]);
// <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>һ<EFBFBD><D2BB>ѡ<EFBFBD><D1A1>
backtrack(state, target, total + choices[i], choices, res);
// <20><><EFBFBD>ˣ<EFBFBD><CBA3><EFBFBD><EFBFBD><EFBFBD>ѡ<EFBFBD>񣬻ָ<F1A3ACBB><D6B8><EFBFBD>֮ǰ<D6AE><C7B0>״̬
state.pop_back();
}
}
/* <20><><EFBFBD><EFBFBD><EFBFBD>Ӽ<EFBFBD><D3BC><EFBFBD> I<><49><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>ظ<EFBFBD><D8B8>Ӽ<EFBFBD><D3BC><EFBFBD> */
vector<vector<int>> subsetSumINaive(vector<int> &nums, int target) {
vector<int> state; // ״̬<D7B4><CCAC><EFBFBD>Ӽ<EFBFBD><D3BC><EFBFBD>
int total = 0; // <20>Ӽ<EFBFBD><D3BC><EFBFBD>
vector<vector<int>> res; // <20><><EFBFBD><EFBFBD><EFBFBD>б<EFBFBD><D0B1><EFBFBD><EFBFBD>Ӽ<EFBFBD><D3BC>б<EFBFBD><D0B1><EFBFBD>
backtrack(state, target, total, nums, res);
return res;
}
/* Driver Code */
int main() {
vector<int> nums = {3, 4, 5};
int target = 9;
vector<vector<int>> res = subsetSumINaive(nums, target);
cout << "<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> nums = ";
printVector(nums);
cout << "target = " << target << endl;
cout << "<EFBFBD><EFBFBD><EFBFBD>к͵<EFBFBD><EFBFBD><EFBFBD> " << target << " <20><><EFBFBD>Ӽ<EFBFBD> res = " << endl;
printVectorMatrix(res);
return 0;
}