且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在字符串中生成字符组合不能完全起作用,为什么?

更新时间:2023-11-14 11:39:58

问题的根源在这里:

  combinations(s.substring(i), prfx + s.charAt(i), n-1);
               ^^^^^^^^^^^^^^

您要遍历字符串中的字符并依次使用每个字符作为前缀,然后进行递归调用以构建其余字符串的组合。但是,如果您仅将原始字符串的子字符串传递给递归调用,则不会生成所有可能的排列。在上述情况下,如您所见,它跳过了 ba,因为当循环到达字符串 ab的第二个字符时(当循环计数器 i 为1时) ),则进行此递归调用: combinations( b, + b,1)。只能生成 bb,不能生成 ba。如果它是 combinations( ab, + b,1),则将同时获得预期的组合 ba和 bb。

You want to loop through the characters in the string and use each character in turn as prefix, then make a recursive call to build the combinations for the rest of the string. However, if you only pass in a substring of the original string into the recursive call, it won't generate all possible permutations. In the above case, as you observed, it skips "ba" because when the loop gets to the 2nd character of the string "ab" (when the loop counter i is 1), this recursive call is made: combinations("b", "" + "b", 1). Which can only generate "bb", not "ba". If it were combinations("ab", "" + "b", 1) instead, you would get both of the expected combinations "ba" and "bb".

因此,您需要将整个字符串传递到每个递归调用中:

So you need to pass the whole string into each recursive call:

  combinations(s, prfx + s.charAt(i), n-1);