用递归函数或使用堆栈生成排列组合数。测试用例: 1) {A, B, C, D, E, F, G, H}中任取三个元素的组合数
时间: 2023-10-02 20:10:15 浏览: 40
递归函数实现:
```
#include <iostream>
#include <vector>
using namespace std;
void combination(vector<char>& arr, vector<char>& res, int pos, int num)
{
if (num == 0) {
// 输出组合结果
for (char c : res) {
cout << c << " ";
}
cout << endl;
return;
}
for (int i = pos; i <= arr.size() - num; i++) {
res.push_back(arr[i]);
combination(arr, res, i + 1, num - 1);
res.pop_back();
}
}
int main()
{
vector<char> arr = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
int num = 3;
vector<char> res;
combination(arr, res, 0, num);
return 0;
}
```
使用堆栈实现:
```
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
void combination(vector<char>& arr, int num)
{
stack<int> s;
s.push(0);
while (!s.empty()) {
int pos = s.top();
s.pop();
if (num == 0) {
// 输出组合结果
for (int i = 1; i < s.size(); i++) {
cout << arr[s.top()] << " ";
s.pop();
}
cout << endl;
}
for (int i = pos; i < arr.size(); i++) {
s.push(i + 1);
combination(arr, num - 1);
}
}
}
int main()
{
vector<char> arr = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H'};
int num = 3;
combination(arr, num);
return 0;
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)