[LeetCode] Word Break II

Source: Internet
Author: User

[LeetCode] Word Break II

Link: https://oj.leetcode.com/problems/word-break-ii/

Given a string s and a dictionary of words dict, add spaces in s to construct a sentence where each word is a valid dictionary word.
Return all such possible sentences.
For example, given
S = "catsanddog ",
Dict = ["cat", "cats", "and", "sand", "dog"].
A solution is ["cats and dog", "cat sand dog"].

Idea: It's also DFS recursive traversal. It is difficult to use dynamic planning. It is required to store the sum of all the results of the word break at the current location. The space is very complicated and cost-effective, and the code writing is still very troublesome.

public class Solution {    public List
 
   wordBreak(String s, Set
  
    dict) {        List
   
     rsList = new ArrayList
    
     ();        if (s == null || s.length() < 1 || dict == null) {            return rsList;        }                wordBreakHelper(s, 0, "", dict, rsList);                return rsList;    }        public void wordBreakHelper(String s, int start, String tempStr, Set
     
       dict, List
      
        rsList) { if (start >= s.length()) { rsList.add(tempStr); return; } for (int i = start + 1; i <= s.length(); i++) { String temp = s.substring(start, i); if (dict.contains(temp)) { String newTempStr; if (tempStr.length() < 1) { newTempStr = temp; } else { newTempStr = tempStr + " " + temp; } wordBreakHelper(s, i, newTempStr, dict, rsList); } } }}
      
     
    
   
  
 

Using this method, there is still a result, TLE. Put the WordBreak method in front, first determine whether word break is available, and then perform the following program to AC

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.