给定两个整数 n
和 k
,返回 1 ... n
中所有可能的 k
个数的组合。
示例 1:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
示例 2:
输入: n = 1, k = 1
输出: [[1]]
提示:
1 <= n <= 20
1 <= k <= n
//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
List<Integer> curList = new ArrayList<>();
combineFunc(result, curList, 1, n, k);
return result;
}
private void combineFunc(List<List<Integer>> result, List<Integer> curList, int i, int n, int k) {
if (i > n) {
return;
}
curList.add(i);
if (curList.size() == k) {
List<Integer> oneRes = new ArrayList<>(curList);
result.add(oneRes);
} else {
combineFunc(result, curList, i + 1, n, k);
}
curList.remove(curList.size() - 1);
combineFunc(result, curList, i + 1, n, k);
}
}
//leetcode submit region end(Prohibit modification and deletion)