1.题目:
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
示例 1:
输入:n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
来源:力扣(LeetCode) 链接:https://leetcode.cn/problems/combinations 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
2.代码
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}
//startIndex用来传入循环开始的结点
public void backtracking(int n,int k,int startIndex){
//递归的终止条件
if(path.size()==k){
result.add(new ArrayList<>(path));//这里是直接传进去用path里面的元素构成的一个新的集合,如果是数组就:new int[]{元素};
return;//结束方法
}
for(int i=startIndex; i<=n; i++){//for循环里面嵌套递归,注意循环的开始和范围
path.add(i);
backtracking(n,k,i+1);//递归的起始结点要+1
path.remove(path.size()-1);//回溯
}
}
}
剪枝优化后:
class Solution {
List<List<Integer>> result = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(n,k,1);
return result;
}
//startIndex用来传入循环开始的结点
public void backtracking(int n,int k,int startIndex){
//递归的终止条件
if(path.size()==k){
result.add(new ArrayList<>(path));//这里是直接传进去用path里面的元素构成的一个新的集合,如果是数组就:new int[]{元素};
return;//结束方法
}
for(int i=startIndex; i<=n-(k-path.size())+1; i++){//for循环里面嵌套递归,注意循环的开始和范围(剪枝操作)
path.add(i);
backtracking(n,k,i+1);//递归的起始结点要+1
path.remove(path.size()-1);//回溯
}
}
}