表格2 ^ n组合字符串

时间:2016-09-01 05:51:14

标签: java algorithm combinations permutation

从给定的字符串,通过考虑公式 2 ^ n(2次幂n)来形成不同的组合集。

例如,请考虑以下示例字符串( AA%0%0%)。其中“%”是可选值,因此“%”可以在字符串组合中添加,也可以从字符串组合中删除,因此可以使用不同的字符串组合,如下所示。

示例字符串: AA%0%0% {%指数位置为[2,4,6]}

示例字符串的不同可能组合 :( 2 ^ n ,其中n = 3(因为“%”计数为3)等于 2 ^ 3 = 8 组合)

为了便于理解,我在下面的组合中将“%”替换为“*”。

1. AA*0*0* [no % omitted]
2. AA*0*0  [index 6 % omitted]   
3. AA*00*  [index 4 % omitted]
4. AA0*0*  [index 2 % omitted]
5. AA*00   [index 4,6 % omitted]
6. AA0*0   [index 2,6 % omitted]
7. AA00*   [index 2,4 % omitted]
8. AA00    [index 2,4,6 % omitted]

现在的问题是,“%”字符串的数量会根据用户输入而有所不同,因此,每次形成这个组合,我想在java中编写一个程序,这将自动为这个组合根据2 ^ n公式。是否有可用的算法?善意的建议。

编辑:

为了更好地理解,我给出了不同的索引,可以由3个计数(2 ^ 3 = 8)组成。这取决于索引位置,例如,%index为2,4,6表示

  1. [2]
  2. [4]
  3. [6]
  4. [2,4]
  5. [2,6]
  6. [4,6]
  7. [2,4,6]
  8. [没有索引(%)删除所有可用字符]

1 个答案:

答案 0 :(得分:1)

You can write a recursive implementation of this. The idea is to check, in the provided string, if the character at index i (which you can pass as paramter to the function) is % or not, if it is, then take two actions:

  • Make a recursive call by not omitting the character at index i (You need to make this call anyway, in both cases, i.e. whether the character at i is % or not)
  • Make a recursive call by omitting the character at index i (which is %, which we have checked)

And when i reaches at the end of the string, you've got yourself a combination. (Since you've done this many recursive calls, so you'll find all of the combinations)

Following, I'll implement using the above idea:

public static void allCombinations(String s, int i){
    if (i < s.length()){
        // Make a recursive call without removing the character
        allCombinations(s, i + 1);

        if (s.charAt(i) == '%'){
            // Remove character at index i and make a recursive call with new string
            String temp = s.substring(0, i) + s.substring(i + 1);
            allCombinations(temp, i);
        }

    }
    else{
        // print the combination found.
        System.out.println(s);
    }
}

and call this recursive implementation by passing 0 as the starting index (because you need to start from 0) like this: allCombinations("AA%0%0%", 0);

EDIT

here, you can find the implementation tested with the provided string (AA%0%0%) on ideone