# LeetCode -- Combination Sum III

Source: Internet
Author: User

LeetCode -- Combination Sum III
Description:

Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination shoshould be a unique set of numbers.

Ensure that numbers within the set are sorted in ascending order.

Example 1:

Input: k = 3, n = 7

Output:

[[1, 2, 4]

Example 2:

Input: k = 3, n = 9

Output:

[[1, 2, 6], [1, 3, 5], [2, 3, 4]

In the Array {1, 2, 3, 4, 5, 6, 7, 8, 9} consisting of 1 to 9, a combination is found, which contains K elements and is n.

Ideas:
It is a typical backtracking problem, which is also a problem: finding all the subproblems in the array nums and the combination of n.
Use the backtracking model to directly solve the problem. During traversal, you only need to collect combinations of k elements.

Implementation Code:

```public class Solution {    public IList

> CombinationSum3(int k, int n)     {       var result = new List

>();    Find(1, n, k, new List

(), ref result);    return result;    }private void Find(int start, int target, int k, IList

current, ref List

> result){if(current.Count > k || target < 0){return;}if(target == 0){if(current.Count == k){result.Add(new List

(current));}//Console.WriteLine(current);return;}for(var i = start; i < 10; i++){current.Add(i);Find(i + 1, target - i, k, current,ref result);current.RemoveAt(current.Count-1);}}}

```

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.