Leetcode 216: Combination Sum III
阿新 • • 發佈:2017-12-02
urn dfs can out () inpu amp ble spa
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, intn, 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