77. 组合
给定两个整数 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.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
递归
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner;
class Solution {
private int n;
private int k;
private List<List<Integer>> ret = new ArrayList<>();
private LinkedList<Integer> path = new LinkedList<>();
private void solve(int idx) {
if (path.size() == k) {
ret.add(new ArrayList<>(path));
return;
}
if (path.size() + (n - idx + 1) < k) {
return;
}
solve(idx + 1);
path.offerLast(idx);
solve(idx + 1);
path.pollLast();
}
public List<List<Integer>> combine(int n, int k) {
this.n = n;
this.k = k;
solve(1);
return ret;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while (in.hasNext()) {
List<List<Integer>> combines = new Solution().combine(in.nextInt(), in.nextInt());
combines.forEach(combine -> {
System.out.println("----");
combine.forEach(System.out::println);
});
}
}
}
迭代
class Solution {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
public List<List<Integer>> combine(int n, int k) {
List<Integer> temp = new ArrayList<Integer>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
// 初始化
// 将 temp 中 [0, k - 1] 每个位置 i 设置为 i + 1,即 [0, k - 1] 存 [1, k]
// 末尾加一位 n + 1 作为哨兵
for (int i = 1; i <= k; ++i) {
temp.add(i);
}
temp.add(n + 1);
int j = 0;
while (j < k) {
ans.add(new ArrayList<Integer>(temp.subList(0, k)));
j = 0;
// 寻找第一个 temp[j] + 1 != temp[j + 1] 的位置 t
// 我们需要把 [0, t - 1] 区间内的每个位置重置成 [1, t]
while (j < k && temp.get(j) + 1 == temp.get(j + 1)) {
temp.set(j, j + 1);
++j;
}
// j 是第一个 temp[j] + 1 != temp[j + 1] 的位置
temp.set(j, temp.get(j) + 1);
}
return ans;
}
}
心之所向,素履以往 生如逆旅,一苇以航

浙公网安备 33010602011771号