为实现遍历所有子序列 ,C++递归函数的模板:
cpp
#include <iostream>
#include <vector>
void Subsequence(std::vector<int>& nums, std::vector<int>& subseq, int start, int k) {
if (subseq.size() == k) {
//此时subseq就是一个符合要求的子序列,可进行相应操作
return;
}
for (int i = start; i < nums.size(); ++i) {
subseq.push_back(nums[i]);
Subsequence(nums, subseq, i + 1, k);//递归调用
subseq.pop_back();
}
}
**C++实战例题:**实现打印所有子序列
cpp
#include <iostream>
#include <vector>
// 打印子序列
void printSubsequence(std::vector<int>& nums, std::vector<int>& subseq, int start, int k) {
if (subseq.size() == k) {
for (int num : subseq) {
std::cout << num << " ";
}
std::cout << std::endl;
return;
}
for (int i = start; i < nums.size(); ++i) {
subseq.push_back(nums[i]);
printSubsequence(nums, subseq, i + 1, k);
subseq.pop_back();
}
}
// 主函数
int main() {
std::vector<int> nums = {1, 2, 3, 4, 5};
int k = 3;
std::vector<int> subseq;
printSubsequence(nums, subseq, 0, k);
return 0;
}
python
cpp
import itertools
def get_subsequences(arr, k):
return list(itertools.combinations(arr, k))
arr = [1, 2, 3, 4, 5]
k = 3
print(get_subsequences(arr, k))
~希望对你有帮助~