Combinations

Leetcode 77.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class Solution {
public List<List<Integer>> combine(int n, int k) {
int[] nums = new int[n];
for(int i = 1;i <= n;i++){
nums[i -1] = i;
}

List<List<Integer>> ans = new ArrayList<>();
List<Integer> list = new ArrayList<>();
backtricking(nums,k,ans,list,0);
return ans;
}
public void backtricking(int[] nums,int k,List<List<Integer>> ans, List<Integer> list,int input){
//recursion stop condition
if(list.size() == k){
//collect the results
ans.add(new ArrayList<>(list));
return;
}

//for loop for this layer
for(int i = input; i < nums.length; i++){
list.add(nums[i]);
//recursion
backtricking(nums,k,ans,list,i + 1);
//undo the previous operations
list.remove(list.size() - 1);
}

}
}