5
社区成员
发帖
与我相关
我的任务
分享
暴力破解法,就是把所有条件,相关情况统统考虑进去,让计算机进行检索,指导得出与之所有条件符合的结果(但是,暴力破解法对计算机资源耗费严重,如果条件太复杂,运算速度缓慢,为了解决这一问题,我们可以事先把与之不相关的条件进行限制,减少计算机的运算量)
1、给出一串序列,输出它的所有子序列。
输入样例:
输入个数:3
输入序列:1,2, 3
输出样例:
1
12
123
23
3
#include<iostream>
using namespace std;
int main(){
int n=0;
cout<<"输入个数:";
cin>>n;
int *a = new int[n];
cout<<"输入序列:";
for(int i=0;i<n;i++){
cin>>a[i];
}
for(int q=0;q<n;q++){//q表示子序列首元素下标
for(int k=q;k<n;k++){
for(int i=q;i<k+1;i++){//k+1表示子序列尾下标
cout<<a[i];
}
cout<<endl;
}
}
return 0;
}
函数封装:
#include<iostream>
#define N 10000
using namespace std;
//输出整数序列的全部子序列
void printSubsequence(int n,int a[]){
for(int h=0;h<n;h++){//子序列首
for(int r=h;r<n;r++){//子序列尾
for(int i=h;i<r+1;i++){//输出子序列
cout<<a[i];
}
cout<<endl;
}
}
}
int main(){
int n=0;
cout<<"输入个数:";
cin>>n;
int *a = new int[n];
cout<<"输入序列:";
for(int i=0;i<n;i++){
cin>>a[i];
}
//printSubsequence(n,a);
return 0;
}
输出:

2、给出两串序列,输出它们相同的子序列。
输入样例:
输入序列1的个数:3
输入序列1元素:1 2 3
输入序列2的个数:2
输入序列2元素:2 3输出样例:
2 长度:1
23 长度:2
3 长度:1
#include<iostream>
#include<string.h>
#define N 10000
using namespace std;
//输出整数序列的全部子序列
void printSubsequence(int n,int a[]){
for(int h=0;h<n;h++){//子序列首
for(int r=h;r<n;r++){//子序列尾
for(int i=h;i<r+1;i++){//输出子序列
cout<<a[i];
}
cout<<endl;
}
}
}
//将全部子序列转化成字符串并存储在字符串数组中
void strSubsequence(int *strlen,int n,int a[],string strs[]){
string str;
int slen=0,si=0;
for(int h=0;h<n;h++){//子序列首
for(int r=h;r<n;r++){//子序列尾
for(int i=h;i<r+1;i++){//输出子序列
str+=a[i]+'0';
}
//cout<<str<<endl;
strs[si++]=str;
slen++;
str="";//清空上一个子串
}
}
for(int i=0;i<slen;i++){
//cout<<strs[i]<<",";
}
*strlen=slen;
}
int main(){
int n=0;
cout<<"输入序列1的个数:";
cin>>n;
int *a = new int[n];
cout<<"输入序列1元素:";
for(int i=0;i<n;i++){
cin>>a[i];
}
//printSubsequence(n,a);
//定义字符串数组
string strs[N];
int strlen=0;
strSubsequence(&strlen,n,a,strs);
//输入序列2
int n2=0;
cout<<"输入序列2的个数:";
cin>>n2;
int *b = new int[n2];
cout<<"输入序列2元素:";
for(int i=0;i<n2;i++){
cin>>b[i];
}
//比较
string str;
for(int h=0;h<n2;h++){//子序列首
for(int r=h;r<n2;r++){//子序列尾
for(int i=h;i<r+1;i++){//输出子序列
str+=b[i]+'0';
}
//cout<<str<<endl;
for(int si=0;si<strlen;si++){
if(str==strs[si]){
cout<<strs[si]<<" "<<"长度:"<<(strs[si]).length()<<endl;
}
}
str="";//清空上一个子串
}
}
return 0;
}
输出:

本例中的子序列满足条件为:在原序列中递增且连续。如果不满足此情况,可能性会更多,建议使用递归算法。