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], ]
public IList<IList<int>> Combine(int n, int k) { var res = new List<IList<int>>(); BackTracking(res,n,k,1,new List<int>()); return res; } private void BackTracking(IList<IList<int>> res, int n,int k, int sentinel, IList<int> cur) { if(k==0) res.Add(new List<int>(cur)); else { for(int i = sentinel; i <= n;i++ ) { cur.Add(i); BackTracking(res,n,k-1,i+1,cur); cur.RemoveAt(cur.Count()-1); } } }