![]() |
In the Combination problem we are given an array of integers and a target number, we have to return all unique possible combinations whose element sum is equal to the target value. There are several approaches available in JavaScript to solve the combination sum problem which are as follows: Brute force Approach ( Using Recursion)We will create a recursive function “findCombination” helper function which will recursively find all combinations that sum up to the target. The base case for function is when the Current Sum equals the target, pushing the Current Combination to the answer array. Recursively call the function and consider two possibilities either we have to pick the element and add it to current Sum or we will skip the current element. Example: To demonstrate Combination sum problem using recursive approach.
Output possible combinations are : [ [ 2, 2, 3 ], [ 7 ] ] Time Complexity: O(2n) Space Complexity: O(n*m) Optimal Approach (Using Dynamic Approach)We use recursion + memoization i.e. top-down dynamic programming approach. Initialize an empty object to store computed results. Define a nested function, dp, for recursive combination finding with memoization. Handle base cases and iterate over nums, recursively calling dp with updated target, then concatenate num with each combination obtained and push to res. Memoize res with the current target as the key. Return the result obtained from dp for the given target. Example: To demonstrate Combination sum problem using recursion with memoization
Output possible combinations are [ [ 2, 2, 3 ], [ 7 ] ] Time Complexity: O(n2 * m) Space Complexity: O(m * k) |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 13 |