写出宝石排列问题的C++代码,并给出测试用例
时间: 2024-03-21 11:44:14 浏览: 61
归并排序、快速排序C++代码(含测试用例)
5星 · 资源好评率100%
宝石排列问题可以用回溯算法来解决。以下是C++代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void backtracking(vector<char>& candidates, vector<char>& path, vector<vector<char>>& result) {
if (path.size() == candidates.size()) {
result.push_back(path);
return;
}
for (int i = 0; i < candidates.size(); i++) {
if (i > 0 && candidates[i] == candidates[i-1] && find(path.begin(), path.end(), candidates[i-1]) == path.end()) {
continue;
}
if (find(path.begin(), path.end(), candidates[i]) != path.end()) {
continue;
}
path.push_back(candidates[i]);
backtracking(candidates, path, result);
path.pop_back();
}
}
vector<vector<char>> getGemstones(string s) {
vector<char> candidates(s.begin(), s.end());
sort(candidates.begin(), candidates.end());
vector<vector<char>> result;
vector<char> path;
backtracking(candidates, path, result);
return result;
}
int main() {
string s = "ABCD";
vector<vector<char>> result = getGemstones(s);
for (auto item : result) {
for (auto c : item) {
cout << c << " ";
}
cout << endl;
}
return 0;
}
```
测试用例:
输入:"ABCD"
输出:
A B C D
A B D C
A C B D
A C D B
A D B C
A D C B
B A C D
B A D C
B C A D
B C D A
B D A C
B D C A
C A B D
C A D B
C B A D
C B D A
C D A B
C D B A
D A B C
D A C B
D B A C
D B C A
D C A B
D C B A
阅读全文