I understand the recursion and find it useful and intuitive while solving problems on trees but for many other problems recursion never fails me to leave puzzled. Recently I was solving the following problem:
Write a recursive function that counts how many different ways you can make change for an amount, given a list of coin denominations.
After trying hard and some Googling I came up with the following solution and thinking about it in details makes me dizzy.
function isEmpty(coins) {
return coins.length === 0;
}
function allButFirst(coins) {
return coins.slice(1);
}
function countChange(money, coins) {
if (money === 0) return 1
else if (money > 0 && !isEmpty(coins)) {
return countChange(money - coins[0], coins) +
countChange(money, allButFirst(coins));
}
else // money < 0
return 0;
}
console.clear();
console.log(countChange(4, [1, 2])); // 3 (1+1+1+1), (1+1+2), (2+2)
AFAIK, the first step in recursive solution is to check if the underlying structure is a recursive one which in my case it yes. But I is there some sort of principle of mental model or anything which could help in designing such solution, even something which could stop me going in wrong direction would work?