# 39. Combination Sum (Medium)

https://leetcode.com/problems/combination-sum/

Given a set of candidate numbers (`candidates`) (without duplicates) and a target number (`target`), find all unique combinations in `candidates` where the candidate numbers sums to `target`.

The same repeated number may be chosen from `candidates` unlimited number of times.

Note:

• All numbers (including `target`) will be positive integers.
• The solution set must not contain duplicate combinations.

Example 1:

```Input: candidates = `[2,3,6,7], `target = `7`,
A solution set is:
[
,
[2,2,3]
]
```

Example 2:

```Input: candidates = [2,3,5]`, `target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
```

## Solutions

• Java
``````public class Solution {
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> rst = new ArrayList<>();
if (candidates == null) return rst;

Arrays.sort(candidates);
combine(rst, new ArrayList<Integer>(), candidates, target, 0);

return rst;
}

private void combine(List<List<Integer>> rst, List<Integer> solution, int[] nums, int target, int depth) {
if (target < 0) {
return;
}

if (target == 0) {
return;
}

for (int i = depth; i < nums.length; i++) {
if (nums[i] > target) {
break;
}

/*
// Uncomment following statements if the nums contains duplicate values
if (i > depth && nums[i] == nums[i - 1]) {
continue;
}
*/
{"ft_lang_label":"__label__en","ft_lang_prob":0.52313066,"math_prob":0.97356623,"size":1493,"snap":"2019-35-2019-39","text_gpt3_token_len":396,"char_repetition_ratio":0.1685695,"word_repetition_ratio":0.00913242,"special_character_ratio":0.31748158,"punctuation_ratio":0.23630136,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.99460936,"pos_list":[0],"im_url_duplicate_count":[null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2019-09-19T22:53:49Z\",\"WARC-Record-ID\":\"<urn:uuid:9e5babff-fbc5-492f-a3bd-d5557d56d65d>\",\"Content-Length\":\"69508\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:033f4ce2-453e-4527-acb9-3403372ca4b9>\",\"WARC-Concurrent-To\":\"<urn:uuid:c7f3c1a4-37c3-472a-a641-f4e913b36591>\",\"WARC-IP-Address\":\"207.246.92.250\",\"WARC-Target-URI\":\"https://www.iovi.com/books/algorithms-manual/leetcode/0039.html\",\"WARC-Payload-Digest\":\"sha1:ZYAOK55NT6YPAQR4JPZ6ZOA43F3IUZZ5\",\"WARC-Block-Digest\":\"sha1:3BVMC34B4CV2VMEM5JG6WQR5SQOMXZCU\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2019/CC-MAIN-2019-39/CC-MAIN-2019-39_segments_1568514573759.32_warc_CC-MAIN-20190919224954-20190920010954-00090.warc.gz\"}"}