Files
leetcode-master/problems/0077.组合.md
youngyangyang04 3ee636ec90 Update
2020-08-21 10:31:54 +08:00

47 lines
933 B
Markdown
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 第77题. 组合
给定两个整数 n 和 k返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
# 思路
# C++ 代码
```
class Solution {
private:
vector<vector<int>> result;
void backtracking(int n, int k, vector<int>& vec, int startIndex) {
if (vec.size() == k) {
result.push_back(vec);
return;
}
// 这个for循环有讲究组合的时候 要用startIndex排列的时候就要从0开始
// 这个过程好难理解,需要画图
for (int i = startIndex; i <= n; i++) {
vec.push_back(i);
backtracking(n, k, vec, i + 1);
vec.pop_back();
}
}
public:
vector<vector<int>> combine(int n, int k) {
vector<int> vec;
backtracking(n, k, vec, 1);
return result;
}
};
```