2 回答
TA贡献8条经验 获得超2个赞
C的语法有点记不清楚了,写了个C++的,楼主看看吧
需要注意的是for循环中在swap位置i和startIdx的值后,需要再swap回去(为什么,楼主可以自己试试看)
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int> > result;
void permutation(vector<vector<int> > & result, vector<int> array, int startIdx, int endIdx) {
if (startIdx == endIdx) {
result.push_back(array);
return;
}
for (int i = startIdx; i <= endIdx; i++) {
int tmp = array[i];
array[i] = array[startIdx];
array[startIdx] = tmp;
permutation(result, array, startIdx+1, endIdx);
tmp = array[i];
array[i] = array[startIdx];
array[startIdx] = tmp;
}
}
int main() {
vector<int> array(3);
for (int i = 0; i < 3; i++) {
array[i] = i;
}
vector<vector<int> > result;
permutation(result, array, 0, array.size() - 1);
for (int i = 0; i < result.size(); i++) {
for(int j = 0; j < result[i].size(); j++) {
cout<<result[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
- 2 回答
- 1 关注
- 2222 浏览
添加回答
举报