Last active
          December 5, 2020 11:51 
        
      - 
      
- 
        Save iJustErikk/bfece3b91e79bccc2f10704617027e13 to your computer and use it in GitHub Desktop. 
  
    
      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
    
  
  
    
  | const bestSum = (targetSum, numbers, memo = new Map()) => { | |
| const key = targetSum + ''; | |
| if (memo.has(key)) return memo.get(key); | |
| if (targetSum === 0) return []; | |
| if (targetSum <= 0) return null; | |
| let smallestSum = null; | |
| for (let num of numbers) { | |
| const remainder = targetSum - num; | |
| const res = bestSum(remainder, numbers, memo); | |
| if (res === null) continue; | |
| const resAndCurrent = [...res, num]; | |
| if (smallestSum === null) smallestSum = resAndCurrent; | |
| if (smallestSum.length > resAndCurrent.length) smallestSum = resAndCurrent; | |
| } | |
| memo.set(key, shortestNum); | |
| return shortestNum; | |
| }; | |
| console.log(bestSum(8, [2, 5, 3])); // -> 5,3 | |
| console.log(bestSum(20, [1,2,3,4,5])) // -> 5,5,5,5 | |
| console.log(bestSum(125, [1,2,4,8,16,32])); // -> 32,32,32,16,8,4,1 | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment