首页 > 代码库 > leetcode216

leetcode216

public class Solution {
    public IList<IList<int>> CombinationSum3(int k, int n)
        {
            int[] num = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
            var result = new List<IList<int>>();
            helper(result, new List<int>(), num, k, n, 0);
            return result;
        }

        public void helper(List<IList<int>> result, List<int> list, int[] num, int k, int target, int start)
        {
            if (k == 0 && target == 0)
            {
                result.Add(new List<int>(list));
            }
            else
            {
                for (int i = start; i < num.Length && target > 0 && k > 0; i++)
                {
                    list.Add(num[i]);
                    helper(result, list, num, k - 1, target - num[i], i + 1);
                    list.RemoveAt(list.Count - 1);
                }
            }
        }
}

https://leetcode.com/problems/combination-sum-iii/#/description

leetcode216