多字符串重构

问题描述:
第一行输入n和m,代表n个字符串,每个字符串长度为m;接下来n行为长度为m的n个字符串,n个字符串构成集合A。
从任意字符串中选取第一个字符为重构字符串第一个字符,从任意字符串中选取第二个字符为重构字符串第二个字符,以此类推,求出以集合A重构出来的字符串集合S。

分析思路:
如用暴力求解,时间复杂度为O(n^m),易运行超时,而且循环层数是变量,不好构建循环体;考虑递归回溯法(背包0-1问题)求取,前一过程已经取得的结果继续保留与栈(实际代码存于vector)中。

代码:

#include<iostream>
#include<vector>
#include<string>
#include<algorithm>
#include<sstream>
using namespace std;

vector<string> all_str;
vector<char> build_str;

void cal(vector<string> &a,int index,int m)
{
    if(index==m)
    {
        string temp;
        for(int i=0;i<m;i++)
        {
            temp=temp+build_str[i];
        }
        auto p=find(all_str.begin(),all_str.end(),temp);
        if(p==all_str.end())
            all_str.push_back(temp);
        return ;
    }
    if(index<m)
    {
        for(int i=0;i<a.size();i++)
        {
            build_str.push_back(a[i][index]);
            cal(a,index+1,m);
            build_str.pop_back();
        }
    }
}

int main()
{
    int n,m;
    istringstream is;
    string s;
    getline(cin,s);
    is.clear();
    is.str(s);
    is>>n>>m;
    vector<string> a;
    for(int i=0;i<m;i++)
    {
        string temp;
        is.clear();
        getline(cin,s);
        is.str(s);
        is>>temp;
        a.push_back(temp);
    }
    all_str=a;
    cal(a,0,m);
    //sort(all.begin(),all.end());
    cout<<"The total size of the rebuild string is: "<<all_str.size()<<endl;
    cout<<"print the total element: "<<endl;
    for(auto i:all_str)
       cout << i << endl;
    return 0;
}

输入:

3 3
ABC
DEF
GHI

输出:

The total size of the rebuild string is: 27
print the total element:
ABC
DEF
GHI
ABF
ABI
AEC
AEF
AEI
AHC
AHF
AHI
DBC
DBF
DBI
DEC
DEI
DHC
DHF
DHI
GBC
GBF
GBI
GEC
GEF
GEI
GHC
GHF

Process returned 0 (0x0)   execution time : 9.127 s
Press any key to continue.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值