LeetCode: Combination Sum IV Solution

1/**
2 * @param {number[]} nums
3 * @param {number} target
4 * @return {number}
5 */
6var combinationSum4 = function (nums, target) {
7 const recursion = (accumulatedSum, memo = new Map()) => {
8 if (memo.has(accumulatedSum)) {
9 return memo.get(accumulatedSum)
10 }
11
12 if (accumulatedSum > target) {
13 return 0
14 }
15
16 if (accumulatedSum === target) {
17 return 1
18 }
19
20 let res = 0
21 for (const num of nums) {
22 res += recursion(accumulatedSum + num, memo)
23 }
24 memo.set(accumulatedSum, res)
25
26 return res
27 }
28
29 return recursion(0)
30}

Comments

Loading comments...

Tags

leetcode

recursion

dynamic programming

Apply and earn a $2,500 bonus once you're hired on your first job!

Clients from the Fortune 500 to Silicon Valley startups

Choose your own rate, get paid on time

From hourly, part-time, to full-time positions

Flexible remote working environment

A lot of open JavaScript jobs!!

Fact corner: Referred talent are 5x more likely to pass the Toptal screening process than the average applicant.

Still hesitate? Read HoningJS author's guide on dealing with Toptal interview process.

Next Post

LeetCode: Remove Nth Node From End Of List

HoningJS

Search Posts