题目地址:Combinations
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<List<Integer>>();
backTracking(res,new ArrayList<Integer>(),1,n,k);
return res;
}
public void backTracking(List<List<Integer>> res, List<Integer> temp, int index, int max, int num){
int size = temp.size();
if(size == num ) {
res.add(new ArrayList<Integer>(temp));
return;
}
for(int i = index; i < max+1; i++){
temp.add(i);
backTracking(res,temp,i+1,max,num);
temp.remove(temp.size()-1);
}
}
}