2017-06-20 47 views
-1

给定一个字符串,我想打印所有的组合,从左到右选择字母:Ex。输入:ABCD 输出: ABC ACD ABD BCD 交流 广告 BC BD CD从左到右打印字符串组合(不是置换)C++

我能做到这一点,但我不能概括它,为前。在字符串abcd中,我可以通过删除只有一个字母来获得所有提到的组合。然后我可以通过删除两个字母等来实现。 代码:

name = "abcdefghi"; 

//删除2个字母

for(int i = 1; i < name.size(); i++){ 

    for(int k = 2; k < name.size(); k++){ 

     for(int j = 0; j < name.size(); j++){ // PRINT ARRAY 
      if(j != i && j != k) cout << name[j]; 
     } 
     cout << endl; 

     } 

    } 

//删除1个字母:

for(int i = 1; i < name.size(); i++){ 

     for(int j = 0; j < name.size(); j++){ // PRINT ARRAY 
      if(j != i) cout << name[j]; 
     } 
     cout << endl; 

    } 

我怎么能概括它,这样我可以先打印1组合字母缺失,然后2个字母丢失,然后3,依此类推... 因为如果我继续这样下去,要得到所有组合中缺少1到n的字母,我需要的for循环n个...

+0

所以你不希望与所有的信件太多的组合?你想从-1字符开始? – koleygr

+0

在你的问题一个简单的答案是把你的循环在另一个循环,将删除字母...你可以开始删除一个或删除零字符 – koleygr

+1

[创建所有可能的K组合中的n项的所有可能的重复]( https://stackoverflow.com/questions/12991758/creating-all-possible-k-combinations-of-n-items-in-c) – ljeabmreosn

回答

0

你可以做这样的例子:

print_combinations(const string& name) { 
    if(name.size() > 1) { 
     for(int i = 0; i < name.size(); ++i) { 
      string name2 = name; 
      name2.erase(i, 1); 
      cout << name2; 
     } 
     for(int i = 0; i < name.size(); ++i) { 
      string name2 = name; 
      name2.erase(i, 1); 
      print_combinations(name2); 
     } 
    } 
} 
0

目前,您可以使用一个计数器,并以此为标志,是这样的:

void print_combinations(const std::string& s) 
{ 
    if (s.size() >= 32) { 
     return; // String too long 
    } 
    std::uint32_t end = 1u << s.size(); 
    for (std::uint32_t i = 0; i != end; ++i) 
    { 
     auto j = i; 
     for (const auto c : s) 
     { 
      if ((j & 1) != 0) { 
       std::cout << c; 
      } 
      j >>= 1; 
     } 
     std::cout << std::endl; 
    } 
} 

Demo