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],
]
看到这种排列的题目 第一想到就是backtracking
backtracking 分两部分
第一部分调用
第二部分函数
函数中
需要一个终止条件
需要一个循环(循环起始位置为start,使每次循环开始不一样)
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> res = new ArrayList<>();
List<Integer> list = new ArrayList<>();
backtracking( res,list, n, k, 1);
return res;
}
public void backtracking(List<List<Integer>> res,List<Integer> list,int n, int k, int start){
//终止条件
if(list.size() == k){
res.add(new ArrayList(list));
return;
}
for( int i =start; i<= n; i++){ //i = start 非常重要, 因为每次循环开始的点不一样
list.add(i);
backtracking( res,list, n, k, i+1);
list.remove(list.size()-1);
}
}
}