Leetcode 77: Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
1 public class Solution { 2 public IList<IList<int>> Combine(int n, int k) { 3 var results = new List<IList<int>>(); 4 DFS(n, k, 1, 1, new List<int>(), results); 5 return results; 6 } 7 8 private void DFS(int n, int k, int start, int cuts, IList<int> result, IList<IList<int>> results) 9 { 10 if (start > n || cuts > k) 11 { 12 if (cuts > k) 13 { 14 results.Add(new List<int>(result)); 15 } 16 17 return; 18 } 19 20 for (int i = start; i <= n; i++) 21 { 22 result.Add(i); 23 DFS(n, k, i + 1, cuts + 1, result, results); 24 result.RemoveAt(result.Count - 1); 25 } 26 } 27 }

浙公网安备 33010602011771号