Table of Contents

# Combination Sum – LeetCode Solution Java , Python 3, Python 2 , C , C++, Best and Optimal Solutions , All you need.

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.

It is **guaranteed** that the number of unique combinations that sum up to `target`

is less than `150`

combinations for the given input.

**Example 1:**

Input:candidates = [2,3,6,7], target = 7Output:[[2,2,3],[7]]Explanation: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.

**Example 2:**

Input:candidates = [2,3,5], target = 8Output:[[2,2,2,2],[2,3,3],[3,5]]

**Example 3:**

Input:candidates = [2], target = 1Output:[]

**Constraints:**

`1 <= candidates.length <= 30`

`1 <= candidates[i] <= 200`

- All elements of
`candidates`

are**distinct**. `1 <= target <= 500`

# C++ Combination Sum LeetCode Solution

```
``````
class Solution {
public:
void Sum(vector<int>& candidates, int target, vector<vector<int> >& res, vector<int>& r, int i)
{
if(target == 0)
{
// if we get exact answer
res.push_back(r);
return;
}
while(i < candidates.size() && target - candidates[i] >= 0)
{
// Till every element in the array starting
// from i which can contribute to the target
r.push_back(candidates[i]);// add them to vector
// recur for next numbers
Sum(candidates,target - candidates[i],res,r,i);
++i;
// Remove number from vector (backtracking)
r.pop_back();
}
}
vector<vector<int>> combinationSum(vector<int>& candidates, int target) {
sort(candidates.begin(),candidates.end()); // sort candidates array
// remove duplicates
candidates.erase(unique(candidates.begin(),candidates.end()),candidates.end());
vector<int> r;
vector<vector<int> > res;
Sum(candidates,target,res,r,0);
return res;
}
};
```

# Java Combination Sum LeetCode Solution

```
```The main idea reminds an approach for solving the coins/knapsack problem – to store the result for all i < target and create the solution from them. For that, for each t from 1 to our target we try every candidate which is less or equal to t in ascending order. For each candidate “c” we run through all combinations for target t-c starting with the value greater or equal than c to avoid duplicates and store only ordered combinations.

```
public class Solution {
public List<List<Integer>> combinationSum(int[] cands, int t) {
Arrays.sort(cands); // sort candidates to try them in asc order
List<List<List<Integer>>> dp = new ArrayList<>();
for (int i = 1; i <= t; i++) { // run through all targets from 1 to t
List<List<Integer>> newList = new ArrayList(); // combs for curr i
// run through all candidates <= i
for (int j = 0; j < cands.length && cands[j] <= i; j++) {
// special case when curr target is equal to curr candidate
if (i == cands[j]) newList.add(Arrays.asList(cands[j]));
// if current candidate is less than the target use prev results
else for (List<Integer> l : dp.get(i-cands[j]-1)) {
if (cands[j] <= l.get(0)) {
List cl = new ArrayList<>();
cl.add(cands[j]); cl.addAll(l);
newList.add(cl);
}
}
}
dp.add(newList);
}
return dp.get(t-1);
}
}
```

# Python 3 Combination Sum LeetCode Solution

```
``````
class Solution(object):
def combinationSum(self, candidates, target):
ret = []
self.dfs(candidates, target, [], ret)
return ret
def dfs(self, nums, target, path, ret):
if target < 0:
return
if target == 0:
ret.append(path)
return
for i in range(len(nums)):
self.dfs(nums[i:], target-nums[i], path+[nums[i]], ret)
```

Array-1180

String-562

Hash Table-412

Dynamic Programming-390

Math-368

Sorting-264

Greedy-257

Depth-First Search-256

Database-215

Breadth-First Search-200

Tree-195

Binary Search-191

Matrix-176

Binary Tree-160

Two Pointers-151

Bit Manipulation-140

Stack-133

Heap (Priority Queue)-117

Design-116

Graph-108

Simulation-103

Prefix Sum-96

Backtracking-92

Counting-86

Sliding Window-73

Linked List-69

Union Find-66

Ordered Set-48

Monotonic Stack-47

Recursion-43

Trie-41

Binary Search Tree-40

Divide and Conquer-40

Enumeration-39

Bitmask-37

Queue-33

Memoization-32

Topological Sort-31

Geometry-30

Segment Tree-27

Game Theory-24

Hash Function-24

Binary Indexed Tree-21

Interactive-18

Data Stream-17

String Matching-17

Rolling Hash-17

Shortest Path-16

Number Theory-16

Combinatorics-15

Randomized-12

Monotonic Queue-9

Iterator-9

Merge Sort-9

Concurrency-9

Doubly-Linked List-8

Brainteaser-8

Probability and Statistics-7

Quickselect-7

Bucket Sort-6

Suffix Array-6

Minimum Spanning Tree-5

Counting Sort-5

Shell-4

Line Sweep-4

Reservoir Sampling-4

Eulerian Circuit-3

Radix Sort-3

Strongly Connected Componen-t2

Rejection Sampling-2

Biconnected Component-1

## Leave a comment below