Generating character combination in a string doesn't work entirely, why?

空扰寡人 提交于 2020-01-03 02:27:34

问题


I'm trying to generate all combinations of the characters in a string. So the first parameter is the string given and the second parameter is the number of letters. So combinations("ab",2) should give me aa, ab, ba, bb and combinations("abc",2) should give me aa, ab, ac, ba, bb, bc, ca, cb, cc, etc.

In the first case my current code gives me aa, ab, bb (so it skips ba). This is my code:

        public static void combinations(String s, int n)
        {
            combinations(s,"",n);
        }


        public static void combinations(String s, String prfx, int n)
        {
            if(n == 0)
            {
                System.out.println(prfx);
            }

            else
            {
                for(int i = 0; i < s.length(); i++)
                {
                    combinations(s.substring(i), prfx + s.charAt(i), n-1);

                }
            }
        }

What am I doing wrong? I would appreciate it if you don't just give me the correct answer, but also give me some explanation so I can learn from it, because I'm not so good at recursion. Thanks.


回答1:


The root of your problem is here:

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

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);



回答2:


This works:

public static void combinations(String s, int n) {
    combinations(s, "", n);
}

public static void combinations(String s, String prfx, int n) {
    if (n == 0) {
        System.out.println(prfx);
    }

    else {
        for (int i = 0; i < s.length(); i++) {
            combinations(s, prfx + s.charAt(i), n - 1);
        }
    }
}


来源:https://stackoverflow.com/questions/9586589/generating-character-combination-in-a-string-doesnt-work-entirely-why

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!