I am following a tutorial on Dynamic Programming on youtube to understand more about Recursive functions, and I am stuck where a spread operator is used.
Code in 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];
}
}
}
This is the code in C# where I’m trying to replicate the function
class HowSumSlow {
static dynamic HowSum(int targetSum, int[] numbers)
{
if (targetSum == 0) return numbers;
if (targetSum < 0) return null;
foreach( var num in numbers){
var remainder = targetSum - num;
int[] remainderResult = HowSum(remainder, numbers);
if (remainderResult != null) {
//Code here//
}
}
return null;
}
static void Main(string[] arg) {
int[] numbers = new int[] { 2, 3 };
Console.WriteLine(HowSum(7, numbers));
}
}
Should I use a Dictionary and use a key? I don’t understand how to work my way around this one.
static Dictionary<int, int[]> spread = new Dictionary<int, int[]>();
static dynamic HowSum(int targetSum, int[] numbers){
...
if(spread.ContainsKey(remainderResult)){
return spread[remainderResult];
}
}