题目
:
给定两个整数 n 和 k,返回 1 … n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
思路:
1、题目要求求子集合、所以子集合中的顺序没有要求
2、注意生成子集合时、path数组下标的确定、这里没有使用正常的 idx 作为下标进行确认、因为 idx 在递归的时候并不是顺序递增的
class Solution {
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();
public static int[] path = new int[100];
public static int K ;
public void roboot(int idx, int n, int k) {
if (k == 0) {
List<Integer> temp = new ArrayList<Integer>();
for (int i = 0; i < K; i++) {
temp.add(path[i]);
}
ans.add(temp);
return;
}
//为什么 i = idx + 1?
//因为为了保证子集合是单调递增的,比如这一次i访问到了2、那么下一层递归中、就需要从2开始查找
for (int i = idx + 1; i <= n; i++) {
path[k - 1] = i; //如果用正常的path[idx] = i 的话、传入第二次递归后、idx并不是挨个递增的,但是k肯定是挨个递减的、所以考虑使用k作为子结果集的下标索引进行记录
roboot(i, n, k - 1);
}
}
public List<List<Integer>> combine(int n, int k) {
ans.clear();
K = k;
roboot(0 ,n, k);
return ans;
}
}