TheAlgorithms/C++ 1.0.0
All the algorithms implemented in C++
Loading...
Searching...
No Matches
subset_sum_dynamic.cpp
Go to the documentation of this file.
1
17#include <cassert>
18#include <iostream>
19#include <unordered_map>
20#include <vector>
21
26namespace dynamic_programming {
27
33namespace subset_sum {
34
43bool subset_sum_recursion(const std::vector<int> &arr, int targetSum,
44 std::vector<std::unordered_map<int, bool>> *dp,
45 int index = 0) {
46 if (targetSum == 0) { // Found a valid subset with required sum.
47 return true;
48 }
49 if (index == arr.size()) { // End of array
50 return false;
51 }
52
53 if ((*dp)[index].count(targetSum)) { // Answer already present in map
54 return (*dp)[index][targetSum];
55 }
56
57 bool ans =
58 subset_sum_recursion(arr, targetSum - arr[index], dp, index + 1) ||
59 subset_sum_recursion(arr, targetSum, dp, index + 1);
60 (*dp)[index][targetSum] = ans; // Save ans in dp map.
61 return ans;
62}
63
70bool subset_sum_problem(const std::vector<int> &arr, const int targetSum) {
71 size_t n = arr.size();
72 std::vector<std::unordered_map<int, bool>> dp(n);
73 return subset_sum_recursion(arr, targetSum, &dp);
74}
75} // namespace subset_sum
76} // namespace dynamic_programming
77
82static void test() {
83 // custom input vector
84 std::vector<std::vector<int>> custom_input_arr(3);
85 custom_input_arr[0] = std::vector<int>{1, -10, 2, 31, -6};
86 custom_input_arr[1] = std::vector<int>{2, 3, 4};
87 custom_input_arr[2] = std::vector<int>{0, 1, 0, 1, 0};
88
89 std::vector<int> custom_input_target_sum(3);
90 custom_input_target_sum[0] = -14;
91 custom_input_target_sum[1] = 10;
92 custom_input_target_sum[2] = 2;
93
94 // calculated output vector by pal_part Function
95 std::vector<int> calculated_output(3);
96
97 for (int i = 0; i < 3; i++) {
98 calculated_output[i] =
99 dynamic_programming::subset_sum::subset_sum_problem(
100 custom_input_arr[i], custom_input_target_sum[i]);
101 }
102
103 // expected output vector
104 std::vector<bool> expected_output{true, false, true};
105
106 // Testing implementation via assert function
107 // It will throw error if any of the expected test fails
108 // Else it will give nothing
109 for (int i = 0; i < 3; i++) {
110 assert(expected_output[i] == calculated_output[i]);
111 }
112
113 std::cout << "All tests passed successfully!\n";
114}
115
120int main() {
121 test(); // execute the test
122 return 0;
123}
for std::vector
Dynamic Programming algorithms.
Functions for [Sub-set sum problem] (https://en.wikipedia.org/wiki/Subset_sum_problem) algorithm.
bool subset_sum_recursion(const std::vector< int > &arr, int targetSum, std::vector< std::unordered_map< int, bool > > *dp, int index=0)
static void test()
Test Function.
bool subset_sum_problem(const std::vector< int > &arr, const int targetSum)
int main()
Main function.