Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- 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;
- };
Add Comment
Please, Sign In to add comment