题目地址:
https://www.lintcode.com/problem/combinations/description
给定正整数 n n n和 k k k,返回所有 ( 1 , 2 , 3 , . . . , n ) (1,2,3,...,n) (1,2,3,...,n)中取出 k k k个数的所有组合。
思路是DFS,从某个数字开始枚举,将其加入一个列表中,然后递归枚举下一个。每次发现列表中有 k k k个数后就说明产生了一种组合,则将其加入最终结果中。代码如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
/**
* @param n: Given the range of numbers
* @param k: Given the numbers of combinations
* @return: All the combinations of k numbers out of 1..n
*/
public List<List<Integer>> combine(int n, int k) {
// write your code here
List<List<Integer>> res = new ArrayList<>();
dfs(n, 1, k, new ArrayList<>(), res);
return res;
}
private void dfs(int n, int pos, int k, List<Integer> cur, List<List<Integer>> res) {
// 如果cur里有了k个数了,就说明产生了一种组合,则将其加入res中
if (cur.size() == k) {
res.add(new ArrayList<>(cur));
return;
}
// 开始从pos处开始枚举,
// 由于从i到n一共有n - i + 1个数,而cur中还需要加k - cur.size()个数,
// 只有当还剩下的数大于cur中还需要添加的数的个数的时候,才去枚举,否则就应该跳出循环
for (int i = pos; k - cur.size() <= n - i + 1; i++) {
cur.add(i);
dfs(n, i + 1, k, cur, res);
cur.remove(cur.size() - 1);
}
}
}
时间复杂度 O ( k ( n k ) ) O(k {n\choose k}) O(k(kn)),空间 O ( k ) O(k) O(k)。