第二十四天| 77. 组合
77_题目关键字:回溯,组合
77_题目链接
代码实现
package LeetCode;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
public class YangSibo_77 {
}
class YangSibo_77_1 {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(1,n,k);
return result;
}
public void backtracking (int startindex,int n,int k) {
if(path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for(int i = startindex;i <= n; i++){
path.add(i);
backtracking(i+1,n,k);
path.removeLast();
}
}
}
class YangSibo_77_2 {
LinkedList<Integer> path = new LinkedList<>();
List<List<Integer>> result = new ArrayList<>();
public List<List<Integer>> combine(int n, int k) {
backtracking(1,n,k);
return result;
}
public void backtracking (int startindex,int n,int k) {
if(path.size() == k) {
result.add(new ArrayList<>(path));
return;
}
for(int i = startindex;i <= n-((k-path.size()))+1; i++){
path.add(i);
backtracking(i+1,n,k);
path.removeLast();
}
}
}
解题注意事项
1、回溯模板要套牢
2、确保startindex是正确的
3、必要时可以进行剪枝