- Notifications
You must be signed in to change notification settings - Fork2.4k
Closed
Description
Bug Report forhttps://neetcode.io/problems/combination-target-sum-ii
Please describe the bug below and include any steps to reproduce the bug or screenshots if possible.?title=Bug Report for combination-target-sum-ii
The given solution for Javascript is quite difficult to read. This one may be more readable and also more efficient.
class Solution { results = []; counts = [] /** * @param {number[]} candidates * @param {number} target * @return {number[][]} */ combinationSum2(nums, target) { const path = []; const available = []; for (const num of nums) { if (!this.counts[num]) { available.push(num); } this.counts[num] = (this.counts[num] || 0) + 1; } this.backtrack(available, target, path, 0); return this.results; } /** * @param {number[]} nums * @param {number} target * @param {number[]} path * @param {number} i * @return {void} */ backtrack(nums, target, path, i) { if (target === 0) { this.results.push([...path]); return; } if (target < 0 || i >= nums.length) { return; } const num = nums[i]; if (this.counts[num] > 0) { path.push(num); this.counts[num] -=1; this.backtrack(nums, target - num, path, i); this.counts[num] += 1; path.pop(); } this.backtrack(nums, target, path, i + 1); }}
Metadata
Metadata
Assignees
Labels
No labels