How to ensure unique results when using DFS for Combination Sum?

I am currently tackling the challenge of solving LeetCode #49 Combination Sum. The objective here is to identify all the distinct combinations that add up to the specified target.

While it's relatively straightforward to find permutations that result in the desired sum, I'm facing a hurdle in modifying my code to only generate unique permutations.

Can someone shed light on the fundamental concept in dynamic programming for obtaining unique results using recursion?

/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum = function (candidates, target) {
    let distinct = []
    let dfs = (candidates, target, list = []) => {
        if (target === 0) {
            distinct.push(list)
            return
        }

        candidates.forEach((candidate, i) => {
            let diff = target - candidate;
            if (diff >= 0) {
                dfs(candidates, diff, [...list, candidate])
            }
        })
    }
    dfs(candidates, target)
    return distinct
};

Input:

[2,3,6,7]
7

My Output:

[[2,2,3],[2,3,2],[3,2,2],[7]]

Desired Output:

[[2,2,3],[7]]

How can I prevent duplicate entries?

Answer №1

An effective strategy for addressing this issue involves breaking down the recursion into two distinct scenarios: one where the initial candidate is utilized, and another where it is not. In the former scenario, the objective is to lessen the total amount required to achieve the goal. Conversely, in the latter scenario, the focus is on reducing the pool of available candidates. To successfully navigate this process, it becomes essential to establish at least two fundamental cases: when the total sum reaches zero and when there are no more candidates left (with consideration for instances where the total may fall below zero as well.) Subsequently, the recursive function calls can be structured in a concise manner:

const combinations = (candidates, target) =>
  candidates.length == 0 || target < 0
    ? []
  : target == 0
    ? [[]]
  : [
      ...combinations(candidates, target - candidates[0]).map(sub => [candidates[0], ...sub]), // include candidates[0]
      ...combinations(candidates.slice(1), target) // exclude candidates[0]
    ]

const displayResults = (candidates, target) => 
  console.log(`combinations(${JSON.stringify(candidates)}, ${target}) => ${JSON.stringify(combinations(candidates, target))} `)

displayResults([2, 3, 6, 7], 7)
displayResults([2, 3, 5], 8)
displayResults([8, 6, 7], 42)

Answer №2

To ensure that the same combination (but in a different order) is not repeated, it is important to use an index and initiate your loop from that index.

let dfs = (candidates, target, list = [], index = 0) => {

This index must be passed into your recursive function (the code has been modified to utilize a for loop for better readability).

 for (let i = index; i < candidates.length; i++) {
    ......
    dfs(candidates, diff, [...list, candidates[i]], i)

Below you can find the working code::

var combinationSum = function(candidates, target) {
  let distinct = []
  // include index parameter in your function
  let dfs = (candidates, target, list = [], index = 0) => {
    if (target === 0) {
      distinct.push(list)
      return
    }

    for (let i = index; i < candidates.length; i++) {
      let diff = target - candidates[i];
      if (diff >= 0) {
        //pass current iteration index
        dfs(candidates, diff, [...list, candidates[i]], i)
      }
    }
  }
  dfs(candidates, target)
  console.log(distinct);
};


combinationSum([2, 3, 6, 7], 7);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What could be the reason my homing missile algorithm is not functioning properly?

The code I'm currently using for my projectile was heavily inspired by an answer I found on a game development forum, but it's not working as expected. Most of the time, the initial direction of the projectile is perpendicular to the target inste ...

I'm having trouble with getting my Bootstrap CSS and JS links to function properly

The paths for the Bootstrap CSS and JS files have been included in the code, but unfortunately, they are not working. Instead, I am getting the following errors in the console: GET http://127.0.0.1:5000/[https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist ...

Using Vuejs to pass the SAVE function into a CRUD component

I am facing a challenge in finding a suitable solution that involves advanced parent-child communication in Vue.js. The scenario is such that there are multiple parent components, each with its own logic on how to save data. On the other hand, there is onl ...

Is it possible to display this code through printing rather than using an onclick event?

I have a puzzle website in the works where users select a puzzle to solve. I am looking for a way to display the puzzles directly on the website instead of using pop-up boxes. I am proficient in various coding languages, so any solution will work for me. ...

Writing a function to determine if an HTML element is present

Is there a way to create a function that checks for the existence of an element with a specific id? I have a list of IDs stored in an array: let CartArray = ["cart-0", "cart-1", "cart-2", "cart-3"]; This is the Java ...

Events related to key press timing in HTML 5 canvas

Currently, I am developing a game similar to Stick Hero for Android using HTML5. I am working on the code that will capture the time of key press (specifically the right arrow key with ASCII 39) in JavaScript and expand a stick accordingly. <!doctype h ...

Open the link and input the text into the text box?

Suppose I have the following JavaScript code: <script language="javascript" type="text/javascript"> function addText() { var newText = document.myForm.inputText.value; document.myForm.description.value += newText; } </script> I want t ...

What is the most effective way to compare two arrays of objects in JavaScript?

I'm working on a function that needs to return an array of elements based on certain filters. Here is the code for the function: filter_getCustomFilterItems(filterNameToSearch: string, appliedFilters: Array<any>) { let tempFilterArray = []; ...

Determine whether AngularJS directive method binding automatically defaults to angular.noop

In my directive, I am passing a function to a plugin which will use it with a specified value. Let's simplify things by ignoring data changes: angular.module('some.directives', []) .directive('myDirective', [, function () { ...

Alter the design when hovering over a relevant element

How can I change hover styles for specific items in React? Currently, all item styles change at once when hovered. I want to only change the style of the selected div when hovering over the add to cart button. Visit this link import React, { useState } fr ...

How can I pass props from a page to components in Next.js using getServerSideProps?

Struggling to fetch the coingecko-api for accessing live bitcoin prices. Trying to pass return props of getServerSideProps to my <CalculatorBuy /> component within the <Main /> component. Facing issues when importing async function in calcula ...

The Ion-button seems to be malfunctioning

I am interested in using special buttons for my ionic 1 project, specifically the ion-button feature outlined on this page: Ionic Buttons. I attempted to create a Round Button and an Outline + Round Button: <h2 class="sub-header" style="color:#4 ...

Anchor checkboxes

I am dealing with a large number of checkboxes that are linked to anchors. Whenever a checkbox is clicked, it navigates to the corresponding anchor on the same page. Is there a more efficient way to implement this? With around 50 checkboxes, my current cod ...

Deliver an extensive JSON reply through a Node.js Express API

When dealing with a controller in a node/express API that generates large data sets for reports, reaching sizes as big as 20Mb per request, maintaining a positive user experience becomes essential. What strategies can be employed to efficiently handle suc ...

Error handling in Angular is not properly managing the custom exception being thrown

I am currently working on an Angular 12 application and I have a requirement to implement a custom ErrorHandler for handling errors globally. When I receive an error notification from the backend, I subscribe to it in the ToolService using this.notificati ...

Pass a JavaScript array variable to a PHP script utilizing jQuery Ajax and receive a string output instead of an array

Whenever I attempt to transmit a JavaScript array to a PHP script via Ajax, the output of $_POST['file_paths'] when var_dumped shows up as a string instead of an array. My goal is to have the output in array format rather than in string format. C ...

Exploring innovative CSS/Javascript techniques for creating intricate drawings

When using browsers other than Internet Explorer, the <canvas> element allows for advanced drawing. However, in IE, drawing with <div> elements can be slow for anything more than basic tasks. Is there a way to do basic drawing in IE 5+ using o ...

Sending an HTTP POST request from Angular 4 to Java SpringMVC results in the issue of POST parameters not

Currently, I am developing a REST API using Java Maven Spring Boot and Spring MVC. I have encountered an issue where Angular POST request parameters are not being recognized by SpringMVC's @RequestParam. Below is the Angular code snippet; saveAsSit ...

What is the best way to access a document that has the lang attribute set to "en" using JavaScript?

I am working on implementing conditional styling in JavaScript by referencing this line of code located before the opening <head> and <body> tags: <html class="js" lang="en"> I want to set a condition so that if the l ...

Variable assigned by Ajax no longer accessible post-assignment

Recently, I've written a script to fetch data from a SQL database and now I'm in the process of creating a JS wrapper for it. Utilizing certain functions, I call the script and extract information from the DB as soon as it becomes available. var ...