Leetcode 216: Combination Sum III
Posted Keep walking
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode 216: Combination Sum III相关的知识,希望对你有一定的参考价值。
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 should be a unique set of numbers.
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]]
1 public class Solution { 2 public IList<IList<int>> CombinationSum3(int k, int n) { 3 var results = new List<IList<int>>(); 4 DFS(k, n, 1, 0, 0, new List<int>(), results); 5 return results; 6 } 7 8 private void DFS(int k, int n, int last, int cur, int sum, IList<int> result, IList<IList<int>> results) 9 { 10 if (cur >= k || sum >= n) 11 { 12 if (cur == k && sum == n) 13 { 14 results.Add(new List<int>(result)); 15 } 16 17 return; 18 } 19 20 for (int i = last; i <= 9; i++) 21 { 22 result.Add(i); 23 DFS(k, n, i + 1, cur + 1, sum + i, result, results); 24 result.RemoveAt(result.Count - 1); 25 } 26 } 27 }
以上是关于Leetcode 216: Combination Sum III的主要内容,如果未能解决你的问题,请参考以下文章
leetcode [216]Combination Sum III
leetcode 216. Combination Sum III
Leetcode题解:L216/Combination Sum III
Leetcode 39 40 216 Combination Sum I II III