77. Combination
Topic link
Source: LeetCode
Link: https://leetcode-cn.com/problems/combinations/
Title description
Given two integers n and k, return all possible combinations of k numbers in 1...n.
Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
Source: LeetCode
Link: https://leetcode-cn.com/problems/combinations
Copyright is owned by LeetCode . For commercial reprints, please contact the official authorization. For non-commercial reprints, please indicate the source.
Topic analysis
Backtracking, draw the tree
k=2 pruning, which is the termination condition,
result, and store the result
list as the current combination
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> result = new ArrayList<>();
backtracking(n, k, result, 1, new ArrayList<>());
return result;
}
// begin从哪个数开始查
public void backtracking(int n, int k, List<List<Integer>> result, int begin, ArrayList<Integer> list){
//递归
//终止条件
if(list.size() == k) {
result.add(new ArrayList<>(list));
return ;
}
for(int i=begin; i<=n; i++){
list.add(i);
backtracking(n, k, result, i+1,list);
list.remove(list.size()-1);
}
}
}