Created
January 9, 2018 02:28
-
-
Save jack5241027/4aa44894dfdc5e5068b387b7e92a78f3 to your computer and use it in GitHub Desktop.
322. Coin Change - BFS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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