输入一个正整数N,输出所有的子集情况和排列情况。代码
时间: 2023-04-10 10:01:14 浏览: 155
好的,这是一个计算问题,我可以回答。以下是代码:
```
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void printVector(vector<int>& v) {
for (int i = 0; i < v.size(); i++) {
cout << v[i] << " ";
}
cout << endl;
}
void subsets(vector<int>& nums, vector<vector<int>>& res, vector<int>& subset, int start) {
res.push_back(subset);
for (int i = start; i < nums.size(); i++) {
subset.push_back(nums[i]);
subsets(nums, res, subset, i + 1);
subset.pop_back();
}
}
void permutations(vector<int>& nums, vector<vector<int>>& res, vector<int>& permutation, vector<bool>& used) {
if (permutation.size() == nums.size()) {
res.push_back(permutation);
return;
}
for (int i = 0; i < nums.size(); i++) {
if (used[i]) {
continue;
}
used[i] = true;
permutation.push_back(nums[i]);
permutations(nums, res, permutation, used);
permutation.pop_back();
used[i] = false;
}
}
int main() {
int n;
cin >> n;
vector<int> nums(n);
for (int i = 0; i < n; i++) {
nums[i] = i + 1;
}
vector<vector<int>> subsetsRes;
vector<int> subset;
subsets(nums, subsetsRes, subset, 0);
cout << "Subsets:" << endl;
for (int i = 0; i < subsetsRes.size(); i++) {
printVector(subsetsRes[i]);
}
vector<vector<int>> permutationsRes;
vector<int> permutation;
vector<bool> used(n, false);
permutations(nums, permutationsRes, permutation, used);
cout << "Permutations:" << endl;
for (int i = 0; i < permutationsRes.size(); i++) {
printVector(permutationsRes[i]);
}
return 0;
}
```
输入一个正整数N,程序会输出所有的子集情况和排列情况。
阅读全文