Problem is to return any one combination from given array that sums up to the target. I'm new to C . Please help me complete the function howSum() below. I can't return null here since the return type is vector. Also I'm having trouble passing the vectors.
//JAVASCRIPT
const howSum = (targetSum, numbers) => {
if (targetSum === 0) return [];
if (targetSum < 0) return null;
for (let num of numbers) {
const remainder = targetSum - num;
const remainderResult = howSum(remainder, numbers);
if (remainderResult !== null)
{
return [...remainderResult, num];
}
}
return null;
};
// C
vector<int> howSum(int targetSum, vector<int> numbers)
{
if(targetSum == 0) return {};
if(targetSum < 0) return; //can't return null here in C
for (int i = 0; i < numbers.size(); i )
{
int remainder = targetSum - numbers[i];
vector<int> remainderResult = howSum(remainder, numbers);
if(pass)
{
pass
}
}
}
CodePudding user response:
You can use C 17 std::optional
and return std::nullopt
when it does not contain value.
#include <optional>
#include <vector>
std::optional<std::vector<int>>
howSum(int targetSum, const std::vector<int>& numbers) {
if (targetSum == 0)
return std::vector<int>{};
if (targetSum < 0)
return std::nullopt;
for (auto numer : numbers) {
const auto remainder = targetSum - numer;
auto remainderResult = howSum(remainder, numbers);
if (remainderResult) {
remainderResult->push_back(targetSum);
return remainderResult;
}
}
return std::nullopt;
}
CodePudding user response:
Let your function return a bool to indicate if the vector result (returned as an out param) is valid or not. It's likely going to be more efficient to pass the array (vector) as an out param reference than as a return value anyway. (Although modern compilers can do some amazing optimizations these days.)
bool howSum(int targetSum, const std::vector<int>& numbers, std::vector<int>& result)
{
result.clear();
if (targetSum == 0) {
return true;
}
if (targetSum < 0) {
return false;
}
for (int num : numbers) {
const int remainder = targetSum - num;
bool recursion_result = howSum(remainder, numbers, result);
if (recursion_result) {
result.push_back(num);
return true;
}
}
return false;
}