题目地址: https://leetcode-cn.com/problems/combinations/
题目描述: 给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
参考代码:
class Solution {
vector<vector<int>> result;
vector<int> path;
void backtrack(int n, int k, int startIndex){
if (path.size() == k) {
result.push_back(path);
return;
}
// for (int i = startIndex; i<=n; i++) {
for (int i = startIndex; i<= n-(k-path.size())+1; i++) { // 剪枝
path.push_back(i);
backtrack(n, k, i + 1);
path.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
result.clear();
path.clear();
backtrack(n, k, 1);
return result;
}
};
参考链接: https://github.com/youngyangyang04/leetcode-master/blob/master/problems/0077.%E7%BB%84%E5%90%88.md
网友评论