title :
Given-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], [up], [1,3], [1,4],]
Exercises
This problem is solved by using DFS (reference work breakii) as a method of cyclic recursive processing of sub-problems. n is the number of cycles, and K is a different number for each attempt. Use of backtracking.
The code is as follows:
1 PublicArraylist<arraylist<integer>> Combine (intNintk) {2arraylist<arraylist<integer>> res =NewArraylist<arraylist<integer>>();3 if(N <= 0| | N <k)4 returnRes;5arraylist<integer> item =NewArraylist<integer>(); 6DFS (N,k,1,item, res);//because it need to begin from 17 returnRes;8 }9 Private voidDfsintNintKintStart, arraylist<integer> item, arraylist<arraylist<integer>>Res) {Ten if(item.size () = =k) { OneRes.add (NewArraylist<integer> (item));//because item is arraylist<t> so it would not be disappear from the stack to stack A return; - } - for(inti=start;i<=n;i++){ the Item.add (i); -DFS (n,k,i+1, item,res); -Item.remove (Item.size ()-1); - } +}
reference:http://blog.csdn.net/linhuanmars/article/details/21260217
Http://www.cnblogs.com/springfor/p/3877168.html
[*] Combination