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);}}}