Recursively spell out the word

I was given the following:

Write a recursive program that, when specifying a line without spaces in it, breaks it into each possible line segmentation into “words”. That is, print out each possible version of the line with spaces in it. The order in which the segmented rows are specified does not matter, but all possible segmentations must be specified without repetition.

and completely lose the way you even start if someone can help.

The output should look like this:

 Enter a string: ABCD

 ABCD
 A BCD
 A B CD
 A B C D
 A BC D
 AB CD
 AB C D
 ABC D
+3
source share
5 answers

I will give you tips to help:

, . , " ". n n-1 , .

, 2, : , .

3, 2 2 . , . , , , .

, .

+5

, ( , ). , 2-5 :

A BCD
A B CD
A B C D
A BC D

, , (ABCD), (A) (BCD). , - , , .

, (AB) (CD), :

AB CD
AB C D
+5

, . Foo(n) , , Foo(n-1) , . GenerateSpaceVariationsOfString(string s), s , . ( , , , , - , .) , s n. , , s - , , GenerateSpaceVariationsOfString(s.substring(1)) {"BCD", "BCD", "BC D", "BC D", ...}, s ABCD. GenerateSpaceVariationsOfString?

( , GenerateSpaceVariationsOfString(s) , s 0 1?)

+2

, , s , s, X of s s\X. , n-1 , , 2^(n-1).

ABC:

  • {'ABC'}//'ABC'
  • {'A', 'B,' C '}//' A ' 1- ' BC '= {' B, 'C'}
  • {'A', 'BC'}// 'A' 2- 'BC' = { 'BC'}
  • {'AB', 'C'}// 'AB' union 1- 'C' = { ''}
  • 1, 2, 3 4 ABC.

:

public static Set<Set<String>> segment(String s) {
    // `s` itself.
    Set<Set<String>> result = new LinkedHashSet<Set<String>>();
    Set<String> root = new LinkedHashSet<String>();
    root.add(s);
    result.add(root);   

    // set union of each substring `X` (prefix) of `s` with `s\X` (rest).
    for (int i = 1; i < s.length(); i++) {   
        String prefix = s.substring(0, i);
        String rest = s.substring(i);
        for (Set<String> segments : segment(rest)) {
            Set<String> segment = new LinkedHashSet<String>();
            segment.add(prefix);
            segment.addAll(segments);
            result.add(segment);
        }
    }
    return result;
}

:

System.out.println(segment("ABC"));
// [[ABC], [AB, C], [A, B, C], [BC, A]]
System.out.println(segment("ABCD"));
// [[D, AB, C], [BCD, A], [D, ABC], [D, A, B, C], [AB, CD], [ABCD], [D, BC, A], [A, B, CD]]
+1

Think of the connection between two letters as one bit. If the bit is 1, you insert a space there; if it is 0, you do not. Therefore, if the length of the string is n, you create a sequence of bits whose length is n-1. Then you process the bit sequence as an unsigned integer and look at all the possible values: 000, 001, 010, etc.

Of course, this is not recursive, so you will not get credit for it.

-1
source

All Articles