比如从一个数组[1,2,3,4,5]
中选择2个,一共有种选择方案,如何列出这些方案
#include<bits/stdc++.h>
using namespace std;
vector<vector<int>> res;
vector<int> nums = {1, 2, 3, 4, 5};
void dfs(int u, int n, vector<int> &path) {
if (n == 0) {
res.push_back(path);
return;
}
if (u >= nums.size())return;
for (int i = u; i < nums.size(); i++) {
path.push_back(nums[i]);
dfs(i + 1, n - 1, path);
path.pop_back();
}
}
int main() {
vector<int> path;
dfs(0, 2, path);
for (auto v:res) {
for (auto i:v) cout << i << " ";
cout << endl;
}
return 0;
}
结果如下:
1 2
1 3
1 4
1 5
2 3
2 4
2 5
3 4
3 5
4 5
网友评论