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

Express.js code is experiencing difficulties with autocomplete functionalities

jQuery autocomplete code example [Express JS code for retrieving data][2\ Example of fetching data in Express JS ...

Encountering a 404 error when trying to access the rxjs node_module

While attempting to compile an angular2 application, I encountered the following issue: Error: XHR error (404 Not Found) loading http://localhost:3000/node_modules/rxjs(…) systemjs.config.js (function(global) { // map tells the System loader whe ...

Is there a dependable resource for mastering Protractor along with the Jasmine Framework in Eclipse using JavaScript?

Starting a new role at my organization where I will be testing Angular JS applications. Can anyone recommend a good website for learning PROTRACTOR with JAVASCRIPT using the JASMINE Framework? (Would prefer if it includes guidance on Eclipse IDE) Thank yo ...

Exploring the best way to use $set in Mongoose for dynamically updating an embedded

I'm currently attempting to create a unique function that can update the value of a specific embedded MongoDB document within an array. The goal is to change the value based on its position. function removeAddress(accountNum, pos) { const remove ...

Ways to display a different div when clicking on a div?

Good afternoon, I've noticed that this question has been asked numerous times before, but none of the solutions provided seem to work for my specific issue. My problem involves a div with the class .title3. I want another div with the class .Content ...

Tips for transferring information from Django to React without relying on a database

Currently, I am in the process of developing a dashboard application using Django and React. The data for the user is being pulled from the Dynamics CRM API. To accomplish this, I have implemented a Python function that retrieves all necessary informatio ...

Having trouble with sending an ajax PUT request

UPDATE: The issue of getting an undefined URI was resolved by storing $(this).attr('red') in a variable. However, the 500 Server error persists. UPDATE: For reference, the complete code can be found on GitHub. Just to ensure nothing was overlook ...

Error encountered while executing node server.js for Azure IoT Hub due to incorrect flags provided in the RegExp constructor

Currently, I am attempting to execute 'node server.js' in order to establish a connection between my Raspberry Pi device and Azure through the Azure IoT Hub. However, upon running the command 'node server.js', an error message is displa ...

Tips for accessing the @keyframes selector and extracting the value from it

In my CSS code, I have a shape element with an animation that spins infinitely for 50 seconds. #shape { -webkit-animation: spin 50s infinite linear; } @-webkit-keyframes spin { 0% { transform: rotateY(0); } 100% { transform: rotateY(-360deg ...

Babel had a SyntaxError in test.jsx file at line 3, position 11 with an Unexpected token

Having trouble converting JSX to JS with Babel? If you're seeing an error like the one below, don't worry - we can help you fix it: The example code in test.jsx is causing a SyntaxError when transformed using babel test.jsx: SyntaxError: test ...

Incorporate a file into all API endpoints with Next.js API functionality

Is there a way to incorporate a "bootstrap" file (a file with side-effects) as the first file included in all Next.js APIs? The main issue is that I have a Winston logger in a file that needs to be added to every API endpoint, but this process hinders dev ...

Arranging the data in the table by alternating rows using Datatables

I need to organize my data in a way that includes an additional row for descriptive information, but this particular row should not be sorted. It is crucial for understanding the rest of the data, so hiding or showing it is not an option. Is it possible t ...

transmitting error messages from a service to a controller in AngularJS

Controller.js var vm = this; vm.admin = {}; vm.add = function () { API.addAdmin(token, vm.admin) .then(function (resp) { vm.hideForm = true; vm.showButton = true; Notify.green(resp); }, function (re ...

Choosing a versatile model field in a Django CMS plugin

Currently, I am developing a Django CMS plugin that includes a model choice field dependent on another field in the form. To update the choices in the model choice field based on the trigger field selection, I am using AJAX. However, when submitting the fo ...

SailsJS failing to detect changes in local JSON file

https://i.stack.imgur.com/RG13Y.png This sailsjs application does not utilize any database. Instead, it relies on multiple JSON files located in the data folder within the root directory. The controller accesses this data as follows: req.session.categori ...

The relentless Livewire Event Listener in JavaScript keeps on running without pausing

I need to create a solution where JavaScript listens for an event emitted by Livewire and performs a specific action. Currently, the JavaScript code is able to listen to the Livewire event, but it keeps executing continuously instead of just once per event ...

Proper method for validating Jwt

Below is the code I have composed: jwt.verify(token.split(':')[1], 'testTest') I am attempting to verify this code in order for it to return true and proceed. The jwt being mentioned here serves as an example payload. Any suggestions ...

Is there a way for me to properly initiate the Material UI Modal from the parent component?

This is the main component: import React from 'react'; import ChildModal from 'ChildModal'; const MainComponent = () => ( <div> <span>Click </span> <a>HERE TO OPEN MODAL</a> <div> ); ...

How can I transfer data from two queries to Jade using Node.js (Express.js)?

I have a database with two tables - one for storing user information and another for managing friendship connections: setting up a friend list in mysql My goal is to create a profile page using Jade, specifically profile.jade: - each user in users ...

Transform strings in a table into integers within a specified scope

My World.json file is quite large and contains extensive data on countries worldwide. I've been utilizing a list to display this data in a table format, with the intention of sorting all values accordingly. However, I have encountered an issue - all m ...