# 【经典问题】遍历得到数组的所有子序列（C++/python）

4 篇文章 0 订阅

#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++实战例题：实现打印所有子序列

#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

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))

~希望对你有帮助~

• 3
点赞
• 0
收藏
觉得还不错? 一键收藏
• 0
评论
01-26 2525
03-26 607

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。