c++ 给定两个整数n和k,返回1 ... n中所有可能的k个数的组合。 示例:输⼊:n = 4, k = 2 输出:[[2,4],[3,4],[2,3],[1,2],[1,3],[1,4],]
时间: 2024-11-09 09:17:39 浏览: 27
在 C++ 中,给定两个整数 `n` 和 `k`,生成所有可能的长度为 `k` 的、从1到 `n` 的数的组合,可以使用回溯算法,特别是递归的方式实现。这是一种经典的动态规划问题,也称为“组合”的问题。以下是一个简单的示例代码:
```cpp
#include <vector>
using namespace std;
void generateCombinations(vector<int>& nums, int start, vector<int>& combination, int k) {
if (combination.size() == k) {
// 当组合大小等于k时,添加到结果列表
nums.push_back(combination);
return;
}
for (int i = start; i <= n; ++i) {
// 将当前数字添加到组合中
combination.push_back(i);
// 继续生成下一位的组合
generateCombinations(nums, i + 1, combination, k);
// 回溯,移除最后一个添加的数字,以便尝试其他选择
combination.pop_back();
}
}
vector<vector<int>> combine(int n, int k) {
vector<vector<int>> result;
vector<int> combination;
generateCombinations(result, 1, combination, k);
return result;
}
// 测试示例
int main() {
int n = 4, k = 2;
vector<vector<int>> combinations = combine(n, k);
for (const auto& combo : combinations) {
cout << "[";
for (int num : combo) {
cout << num << ", ";
}
cout << "]" << endl;
}
return 0;
}
```
当你运行这个程序,它将输出给定示例中提到的所有可能组合。例如,对于输入 `n=4` 和 `k=2`,你会得到类似 `[2, 4]`、`[3, 4]` 等等的结果。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)