Press n or j to go to the next uncovered block, b, p or k for the previous block.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | 40x 1x 190x 190x 184x 173x 180x 168x 168x 5x 5x | /** * Return true if the target sum can be constructed using the numbers * from the array. False otherwise. * * The numbers of the array can be used more than once. * * All input numbers are non-negative. * * The brute-force implementation has the following complexity: * - Time complexity: O(n^m) * - Space complexity: O(m) * * The memoised version has the following complexity: * - Time complexity: O(n * m) * - Space complexity: O(m) * * Where * - "n" is the size of the array of numbers (branching factor) * - "m" is the target sum (height of the tree) * * @param targetSum the number to construct summing the numbers from the arrays * @param numbers the array of numbers * @param buffer the object used for memoisation * @returns true if the target sun can be constructed */ export default function canSum( targetSum: number, numbers: number[], buffer: Record<number, boolean> = {}, ): boolean { Iif (targetSum in buffer) return buffer[targetSum]; if (targetSum === 0) return true; if (targetSum < 0) return false; for (const number of numbers) { if (canSum(targetSum - number, numbers, buffer)) { buffer[targetSum] = true; return buffer[targetSum]; } } buffer[targetSum] = false; return buffer[targetSum]; } |