生成字符串的所有组合的算法 [英] Algorithm to generate all combinations of a string

查看:109
本文介绍了生成字符串的所有组合的算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上找到了一个链接,显示了生成字符串所有组合的算法: http:// www。 mytechinterviews.com/combinations-of-a-string

I found a link online that shows an algorithm to generate all combinations of a string: http://www.mytechinterviews.com/combinations-of-a-string

算法复制如下。

void combine(String instr, StringBuffer outstr, int index)
{
    for (int i = index; i < instr.length(); i++)
    {
        outstr.append(instr.charAt(i));
        System.out.println(outstr);
        combine(instr, outstr, i + 1);
        outstr.deleteCharAt(outstr.length() - 1);
    }
} 

combine("abc", new StringBuffer(), 0);

我不明白的是这条线:

outstr.deleteCharAt(outstr.length() - 1);

如果我删除这一行,该程序显然不再有效,但为什么需要在第一名?我理解递归的想法,我们改变一个初始字符并递归剩余的字符,但deleteChar行似乎在逻辑上不适合任何地方。添加outstr.deleteCharAt行的原因是什么?

If I remove this line, the program obviously does not work anymore, but why is this needed in the first place? I understand the recursive idea where we vary an initial character and recurse on the remaining characters, but the deleteChar line does not seem to fit in logically anywhere. What was the reason for adding the outstr.deleteCharAt line?

推荐答案

调用 outstr.deleteCharAt 通过删除 outstr 的最后一个字符来计算 outstr.append 的效果。

The call of outstr.deleteCharAt counters the effect of outstr.append by deleting the last character of the outstr.

每次循环迭代过程如下:

Each loop iteration proceeds as follows:


  1. 追加一个字符

  2. 打印结果

  3. i + 1
  4. $ b $级别执行递归调用b
  5. 删除我们在第1步添加的字符

  1. append a character
  2. print the result
  3. perform a recursive invocation at the level i+1
  4. remove the character we added at step 1

这篇关于生成字符串的所有组合的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆