The objective is to return true if the sum
can be made by adding up elements from a given vector. The vector elements maybe used and reused in any order.
Example:
sum = 7, list = [4,5]
return false because you can't use these list elements to make 7
sum = 9 or 5 or 20 or 8, list = [4,5]
return true because 9 = 4+5, 5 is in list already, 20 = 5+5+5+5, 8 = 4 + 4
I do not know why canSum
is not returning anything. When targetSum
reaches 0, canSum
should return true
, and then in memo
we emplace
(remainder, true). However, the program is not returning anything. Why is that?
#include <iostream>
#include <vector>
#include <map>
using namespace std;
bool canSum(int targetSum, vector<int> &vec, map<int, bool> &memo) {
int remainder;
if (memo[targetSum] == true)
return true;
else if (targetSum == 0)
return true;
else if (targetSum < 0)
return false;
else
for (auto i : vec) {
remainder = targetSum - i;
if (canSum(remainder, vec, memo)) {
memo.emplace(remainder, true);
return true;
}
}
memo.emplace(remainder, false);
return false;
}
int main() {
vector<int> vector1{7, 14};
int sum = 300;
map<int, bool> memo;
if (canSum(sum, vector1, memo))
cout << "true";
else
cout << "false";
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…