第77题. 组合
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
思路:
使用回溯算法,
LinkedList path: 来存储路径
List<List> res: 存储结果
backtrack(int n,int k,int start): 递归函数
(path.size()==k: 单层递归结束条件,也是res收集结果条件
单层递归逻辑:
j <= n-(k-path.size())+1: 剪枝优化
for (int j = start; j <= n-(k-path.size())+1; j++) {
path.add(j);
backtrack(n,k,j+1);
path.removeLast();
}
注意:由于是组合问题,不是排列问题,所以使用start来移动元素。
import java.util.*;
//组合问题
public class Combination {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
int k = scanner.nextInt();
backtrack(n,k,1);
System.out.println(Arrays.toString(res.toArray()));
}
static List<List<Integer>> res = new ArrayList<List<Integer>>();
static LinkedList<Integer> path = new LinkedList<>();
public static void backtrack(int n,int k,int start){
if (path.size()==k){
res.add(new ArrayList<>(path));
return;
}
for (int j = start; j <= n-(k-path.size())+1; j++) {
path.add(j);
backtrack(n,k,j+1);
path.removeLast();
}
}
}