Monday, August 22, 2016

Leetcode 77. Combinations

 public class Solution {  
   public IList<IList<int>> Combine(int n, int k) {  
     List<IList<int>> ret = new List<IList<int>>();  
     if (n <= 0 || n < k)  
     {  
       return ret;  
     }  
     List<int> path = new List<int>();  
     dfs(n, k, 0, path, ret);  
     return ret;  
   }  
   public void dfs(int n, int k, int index, List<int> path, List<IList<int>> ret)  
   {  
     if (path.Count == k)  
     {  
       List<int> res = new List<int>(path);  
       ret.Add(res);  
       return;  
     }  
     for (int i = index; i < n; i++)  
     {  
       path.Add(i + 1);  
       dfs(n, k, i+1, path, ret);  
       path.RemoveAt(path.Count - 1);  
     }  
   }  
 }  

No comments:

Post a Comment