Is it mandatory for backtracking algorithm to start from back? -


I have solved wordbreakII problem by backtracking algorithm, following code:

  public static list & Lt; String & gt; Wordbreak (string s, set  dct) {list & lt; String & gt; Word = new arreelist & lt; String & gt; (); Int len ​​= s.length (); For (int i = len -1; i> = 0; i--) {string last = s.sstring (i, len); // Get the last word and do the rest if (warp container (last)) {if (i == 0) {words.add (last); } Other {stay the string = s.sstring (0, i); & Lt; String & gt; RemainSet = wordBreak (stay, dict); If (Rahasnat! = Null) {for (string item: living condition) {words.add (item + "" + final); }}}}} Return word; }   

If I try to process in the front, the result should be the same.

  Public Stable List & lt; String & gt; WordbreakerFront (string s, set  gtk) {list & lt; String & gt; Word = new arreelist & lt; String & gt; (); Int len ​​= s.length (); For (int i = 1; i & lt; = len; i ++) {string front = s.sstring (0, i); If (learned (front)) (if (i == lane) {words.add (front);} other {// get the word of the front and rest the process is string = s.sstring (i, len) ; {String.add (front + "" + items) for {string items: living space} {if it is! = Faucet}; & lt; string & gt; RemainSet = wordBreak (stay, dict); ;}}}}} Return word;}   

Front-tracking also works (can produce the right output) but it comes with less efficientity, then this timeframe test I in Am. After failing on this issue:

// Last execute input: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaab", [ "come", "", "aaa", "aaaa", "aaaaa", "aaaaaa" "

Thank you

Both of them have the complexity of exponential time in the worst case scenario. It is a matter of luck that one was passed earlier and the other one failed (if you reverse the input word and All words in the dictionary change, then First will work a very long time).

Comments

Popular posts from this blog

java - ImportError: No module named py4j.java_gateway -

python - Receiving "KeyError" after decoding json result from url -

C++ Array Type Not Assignable in Copy Constructor -