Skip to content

Instantly share code, notes, and snippets.

@jack5241027
Created January 9, 2018 02:28
Show Gist options
  • Select an option

  • Save jack5241027/4aa44894dfdc5e5068b387b7e92a78f3 to your computer and use it in GitHub Desktop.

Select an option

Save jack5241027/4aa44894dfdc5e5068b387b7e92a78f3 to your computer and use it in GitHub Desktop.
322. Coin Change - BFS
var coinChange = function (coins, amount) {
if (!amount) return amount;
let smallest = Infinity;
const helper = (val, path) => {
for (let i = 0; i < coins.length; i++) {
const nextVal = val + coins[i];
if (nextVal < amount) {
helper(nextVal, path.concat(coins[i]));
} else if (nextVal === amount) {
if ((path.length + 1) < smallest) {
smallest = path.length + 1;
}
}
}
};
for (let i = 0; i < coins.length; i++) {
if (coins[i] === amount) {
smallest = 1;
} else {
helper(coins[i], [coins[i]]);
}
}
return smallest === Infinity ? -1 : smallest;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment