欧卡2中文社区

 找回密码
 立即注册

QQ登录

只需一步,快速开始

需要三步,才能开始

只需两步,慢速开始

欧卡2入门方向盘选莱仕达V9莱仕达折叠便携游戏方向盘支架欢迎地图Mod入驻
查看: 5857|回复: 2
收起左侧

[编程] 字符串问题

[复制链接]
知行 发表于 2013-4-14 19:44 | 显示全部楼层 |阅读模式
已知有两个字符a和b,要求列出所有长度小于n的由a和b组成的字符串(n由键盘获得)。
比如n=3时应打印出如下结果:
a,b
aa, ab, ba, bb
aaa, aab, aba, abb, baa, bab, bba, bbb
 楼主| 知行 发表于 2013-4-15 18:26 | 显示全部楼层
谭神代码
#include<iostream>
#include<vector>
using namespace std;
void fun(int k,vector<char> v)
{
    if(k>0)
    { 
        for(char i=97;i<99;i++)
        {
            v.push_back(i);
            if(k==1)
            {
                for(int j=0;j<v.size();j++)
                    cout<<v[j];
                cout<<endl;       
            }
            else
            {
                fun(k-1,v);
            }
            v.pop_back();       
        }
    } 
}
int main()
{
    vector<char> v;
    for(int i=1;i<4;i++)
    {
        fun(i,v); 
        v.clear();   
    }
    while(1);
    return 0;
}
 楼主| 知行 发表于 2013-4-15 18:27 | 显示全部楼层
燕神代码
#include<iostream> 
#include<queue>
using namespace std;

int main()
{
 int i,tag=1,conut;
 string a="",newstring;
 queue<string> q1,q2;
 q1.push(a);
 while(1)
 {
  if(tag==1)
  {
   conut=q1.size();
    for(i=0;i<conut;i++)
  {
   a=q1.front();q1.pop();
   newstring=a+"a";
   q2.push(newstring); 
   cout<<newstring<<" ";
   newstring=a+"b"; 
   q2.push(newstring); 
   cout<<newstring<<" ";                    
  }
  tag=2;        
  }
  else if(tag==2)
  {
     conut=q2.size();
     for(i=0;i<conut;i++)
  {
   a=q2.front();q2.pop();
   newstring=a+"a";
   q1.push(newstring); 
   cout<<newstring<<" ";
   newstring=a+"b"; 
   q1.push(newstring); 
   cout<<newstring<<" ";                    
  }
  tag=1;      
  }
  cout<<endl;
  system("pause");        
 }
 system("pause"); //4
 return 0;
}
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

联系我们|手机版|欧卡2中国 ( 湘ICP备11020288号-1 )

GMT+8, 2024-5-21 02:35 , Processed in 0.044683 second(s), 7 queries , Redis On.

Powered by Discuz! X3.4

Copyright © 2001-2023, Tencent Cloud.

快速回复 返回顶部 返回列表