leetcode 77 combinations

Given two integers n and k, return all possible combinations of k numbers out of 1 … n.

Example:

1
2
3
4
5
6
7
8
9
10
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

  • bfs回溯就好了
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class  {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
List<Integer> current = new ArrayList<Integer>();
bfs(result, current, n , k, 1);
return result;
}
public void bfs(List<List<Integer>> result, List<Integer> current, int n, int k, int c){
if(current.size() == k){
result.add(new ArrayList<Integer>(current));
return ;
}
for(int i=c; i<=n; i++){
current.add(i);
bfs(result, current, n ,k, ++c);
current.remove(current.size()-1);

}
}
}