-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDay29.cpp
More file actions
78 lines (64 loc) · 1.76 KB
/
Day29.cpp
File metadata and controls
78 lines (64 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
/*
This problem was asked by Google.
Given a list of integers S and a target number k, write a function that returns a subset of S that adds up to k. If such a subset cannot be made, then return null.
Integers can appear more than once in the list. You may assume all numbers in the list are positive.
For example, given S = [12, 1, 61, 5, 9, 2] and k = 24, return [12, 9, 2, 1] since it sums up to 24.
*/
#include <bits/stdc++.h>
using namespace std;
bool subsetSumDP(const vector<int> &S, int k, int index,
map<pair<int, int>, bool> &memo,
vector<int> &result)
{
if (k == 0)
return true;
if (index >= S.size() || k < 0)
return false;
pair<int, int> key = {index, k};
if (memo.count(key))
return memo[key];
// Include current element
result.push_back(S[index]);
if (subsetSumDP(S, k - S[index], index + 1, memo, result))
{
memo[key] = true;
return true;
}
result.pop_back(); // backtrack
// Exclude current element
if (subsetSumDP(S, k, index + 1, memo, result))
{
memo[key] = true;
return true;
}
memo[key] = false;
return false;
}
vector<int> subsetSum(const vector<int> &S, int k)
{
map<pair<int, int>, bool> memo;
vector<int> result;
if (subsetSumDP(S, k, 0, memo, result))
{
return result;
}
return {};
}
int main()
{
vector<int> S = {12, 1, 61, 5, 9, 2};
int k = 24;
vector<int> result = subsetSum(S, k);
if (!result.empty())
{
cout << "Subset that sums to " << k << ": ";
for (int num : result)
cout << num << " ";
cout << endl;
}
else
{
cout << "No subset found that sums to " << k << endl;
}
return 0;
}