题目
地址:https://leetcode.com/problems/combinations/
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
DFS深度优先回溯
思路解析:
- 遍历所有数据,要么选择,要么不选择
list.remove(list.size() - 1)
。 - 回溯的起点数据为
1
, 每次递归调用数字个数参数k的变化为k -1
。 - 当
k == 0
的时候,把数据添加到结果列表中. - 提升效率亮点,循环遍历数据只考虑有效数据
i <= n - k + 1
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
if (n == 0 || k == 0) {
return resultList;
}
// dfs
dfs(n, k, resultList, new ArrayList<Integer>(), 1);
return resultList;
}
public void dfs(int n, int k, List<List<Integer>> resultList, List<Integer> list, int start) {
if (k == 0) {
resultList.add(new ArrayList<Integer>(list));
return;
}
for (int i = start; i <= n - k + 1; i++) {
// [1, 2], [1, 3], [1, 4]
// [2, 3], [2, 4]
// [3, 4]
list.add(i);
dfs(n, k - 1, resultList, list, i + 1);
list.remove(list.size() - 1);
}
}
公式算法C(n,k)=C(n-1,k-1)+C(n-1,k)
// based on C(n,k)=C(n-1,k-1)+C(n-1,k)
public List<List<Integer>> combineBaseOnFormular(int n, int k) {
List<List<Integer>> resultList = new LinkedList<List<Integer>>();
if (n < k || k == 0) {
return resultList;
}
resultList = combineBaseOnFormular(n - 1, k - 1);
// if at this point resultList is empty, it can only be that k - 1 == 0,
// n - 1 < k - 1 is not possible since n >= k (if n < k, the function would have already returned at an early point)
if (resultList.isEmpty()) {
resultList.add(new LinkedList<Integer>());
}
for (List<Integer> list: resultList) {
list.add(n);
}
resultList.addAll(combineBaseOnFormular(n - 1, k));
return resultList;
}