给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
static List<List<Integer>> lists;
public static List<List<Integer>> combine(int n, int k) {
lists = new ArrayList<>();
search(1, n, k, new ArrayList<>(n));
return lists;
}
//为了去重,需要使用start标记上次搜索到了哪个位置,下次从start+1开始搜索
public static void search(int start, int n, int remain, List<Integer> list) {
for (int i = start; i <= n - remain + 1; i++) {
list.add(i);
if (remain == 1) {
lists.add(new ArrayList<>(list));
} else {
search(i + 1, n, remain - 1, list);
}
list.remove(list.size() - 1);
}
}