题目:
给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
思路:回溯法
Java代码如下:
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
combineBack(n,k,1,result,new ArrayList<>());
return result;
}
public void combineBack(int n,int k,int start,List<List<Integer>> result,List<Integer> tmp){
if(tmp.size()==k){
result.add(new ArrayList<>(tmp));
return;
}else if(tmp.size()>k){
return;
}
for(int i=start;i<=n;i++){
tmp.add(i);
combineBack(n,k,i+1,result,tmp);
tmp.remove(tmp.size()-1);
}
}
}