TLE problem for my dp solution


  • 0
    D
    public class Solution {
        public List<String> wordBreak(String s, Set<String> wordDict) {
            List<List<String> > dp = new ArrayList<List<String> >();
            List<String> wordBreak, temp;
            int i, j, k;
            String sub;
            
            for (i = 0; i < s.length(); i++) {
                wordBreak = new ArrayList<String>();
                for (j = 0; j <= i; j++) {
                    sub = s.substring(j, i + 1);
                    if (j == 0 && wordDict.contains(sub)) {
                        wordBreak.add(sub);
                    } else if (j > 0 && dp.get(j - 1).size() != 0 && wordDict.contains(sub)) {
                        temp = dp.get(j - 1);
                        for (k = 0; k < temp.size(); k++)
                            wordBreak.add(temp.get(k) + " " + sub);
                    }
                }
                dp.add(wordBreak);
            }
            
            return dp.get(s.length() - 1);
        }
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.