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],[1,2],[1,3],[1,4]]
The idea is still the same, backtracking algorithm, just a little bit of a judgment condition.
Public classSolution {/** * @paramN:given the range of numbers *@paramK:given The numbers of combinations *@return: All the combinations of K numbers out of 1..N*/ PublicList<list<integer>> Combine (intNintk) {//Write your code hereList<List<Integer>> result =NewArraylist<list<integer>>(); if(N < 1 | | k >N)returnresult; List<Integer> line =NewArraylist<integer>(); Helper (result, line, N, K,1); returnresult; } Public voidHelper (list<list<integer>> result, list<integer> line,intNintKintstart) { if(line.size () = =k) {Result.add (NewArraylist<integer>(line)); return; } for(inti = start; I <= N; i++) {line.add (i); Helper (result, line, N, K, I+ 1); Line.remove (Line.size ()-1); } return; } }
Lintcode-medium-combinations