> For the complete documentation index, see [llms.txt](https://algorithm.prettylog.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/dynamic-programming/2023-0709-39.-combination-sum.md).

# 2023 0709 39. Combination Sum

39\. Combination SumMedium16.6K334Companies

Given an array of **distinct** integers `candidates` and a target integer `target`, return *a list of all **unique combinations** of* `candidates` *where the chosen numbers sum to* `target`*.* You may return the combinations in **any order**.

The **same** number may be chosen from `candidates` an **unlimited number of times**. Two combinations are unique if the

frequency of at least one of the chosen numbers is different.

The test cases are generated such that the number of unique combinations that sum up to `target` is less than `150` combinations for the given input.

**Example 1:**

<pre><code><strong>Input: candidates = [2,3,6,7], target = 7
</strong><strong>Output: [[2,2,3],[7]]
</strong><strong>Explanation:
</strong>2 and 3 are candidates, and 2 + 2 + 3 = 7. Note that 2 can be used multiple times.
7 is a candidate, and 7 = 7.
These are the only two combinations.
</code></pre>

**Example 2:**

<pre><code><strong>Input: candidates = [2,3,5], target = 8
</strong><strong>Output: [[2,2,2,2],[2,3,3],[3,5]]
</strong></code></pre>

**Example 3:**

<pre><code><strong>Input: candidates = [2], target = 1
</strong><strong>Output: []
</strong></code></pre>

**Constraints:**

* `1 <= candidates.length <= 30`
* `2 <= candidates[i] <= 40`
* All elements of `candidates` are **distinct**.
* `1 <= target <= 40`

{% embed url="<https://leetcode.com/problems/combination-sum/description/>" %}

> time: O(2^n or n^m) ?

> space: O(m^2) ?

```jsx
/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */

let answer = [];
var combinationSum = function(candidates, target) {
    answer = [];
    findCombination(candidates, 0, target);
    return answer;
};

function findCombination(arr, idx, target, currArr = [], currSum = 0) {
    for (let i = idx; i < arr.length; i++) {
        const curr = arr[i];
        if (currSum === target) {
            answer.push(currArr);
            break;
        } else if (currSum > target) {
            continue;
        } else if (currSum < target) {
            findCombination(arr, i, target, [...currArr, curr], currSum + curr);
        }
    }

}

/**
points
1. how to create combination with using duplicate allowed
2. new reference
3. when to stop?
4. time? 2 <= num <= 40, 1 <= target <= 40
    - depth 20 => N
    - time 20 => N
 */
```

Hao

```javascript
var combinationSum = function(candidates, target) {
    const answer = [];
    candidates.forEach((candidate, index) => {
        const nextTarget = target - candidate;
        if (nextTarget === 0) {
            answer.push([target]);
        }
        if (nextTarget > 0) {
            combinationSum(candidates.slice(index), nextTarget).forEach((partialSum) => {
                answer.push([candidate, ...partialSum])
            })
        }
    })

    return answer;
};
```

Choozil

```javascript
/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */

let res;

var combinationSum = function(candidates, target) {
   
    res = []; 
    
    const backtrack = (sum, selected ,idx) => {
        if(sum === target){            
            res.push(selected);
            return;
        }
        
        else if(sum > target){
            return;
        } 
        
        for(let i=idx; i<candidates.length;i++){
            selected.push(candidates[i]);
            sum += candidates[i];
            backtrack(sum, [...selected], i);
            selected.pop();
            sum -= candidates[i];
        }
    }
    
    backtrack(0, [], 0);
    return res;
};
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://algorithm.prettylog.com/top-75-leetcode-questions-to-save-your-time/problems/dynamic-programming/2023-0709-39.-combination-sum.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
