Given two integersNAndK, Return all possible combinationsKNumbers out of 1...N.
For example,
IfN= 4 andK= 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4],]
Search for a forest using DFS. During the search, the child value must be greater than the parent node value for pruning. The forest is in the following shape:
Suppose n = 4, K = 2;
The Code is as follows:
1 public class Solution { 2 private void comb(int n,int k,int level,List<List<Integer>> answer,List<Integer> result){ 3 if(level == k){ 4 ArrayList<Integer> temp = new ArrayList<Integer>(result); 5 answer.add(temp); 6 7 return; 8 } 9 for(int i = 1;i <= n;i++){10 if(result.isEmpty() || result.get(result.size()-1) < i){11 result.add(i);12 comb(n, k, level+1, answer, result);13 result.remove(result.size()-1);14 }15 }16 }17 public List<List<Integer>> combine(int n, int k) {18 List<List<Integer>> answer = new ArrayList<List<Integer>>();19 List<Integer> result = new ArrayList<Integer>();20 21 comb(n, k, 0, answer, result);22 23 return answer;24 }25 }
Level records the current search level. If K is equal, a combination is found.