给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2 输出: [ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
思路:深度优先搜索dfs,先搜索idx = 0的,再往上传递,每传递一次k-1,一直到k = 0,这时候要回溯,把最顶端的那个传递值,减去,然后在回溯到上一层,搜索idx+1。
java版:
class Solution {
public static List<List<Integer>> ans = new ArrayList<List<Integer>>();//结果
public static int[] path = new int[100];//路径
public static int K = 0;
public void robot(int idx,int n,int k){//idx in [0,n]表示最后的所搜索到的数字,最后选择的数字
//边界条件
if (k == 0){
//record ans
List<Integer> tmp = new ArrayList<Integer>();
for(int i = 0;i< K;i++){
tmp.add(path[i]);
}
ans.add(tmp);
return ;
}
//递归
for(int i = idx + 1;i <= n;i++){ //i 表示当前搜索的数字,下一层搜索的范围
path[k-1] = i;
robot(i,n,k-1);
}
}
public List<List<Integer>> combine(int n, int k) {
ans.clear();//leetcood程序执行是反复调用的,所以要清一下
K = k;
robot(0,n,k);//0表示下标开始的地方
return ans;
}
}
python版:
class Solution:
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
self.ans = []
self.robot(0,[],n,k)
return self.ans
def robot(self,idx,tmp,n,k):
if k == 0:
self.ans.append(tmp[:])
for i in range(idx+1,n+1):
tmp.append(i)
self.robot(i,tmp,n,k-1)
tmp.pop()
# from itertools import combinations
# s = list(range(1, n + 1))
# return list(combinations(s, k))