Share my DP JavaScript solution


  • 0
    L
    var wordBreak = function(s, wordDict) {
      var res = [];
      var from = [];
      from[0] = [0];
      for (var i = 1; i <= s.length; i++) {
        from[i] = [];
        for (var j = 0; j < i; j++) {
          if (from[j].length && wordDict.has(s.substring(j, i))) {
            from[i].push(j);
          }
        }
      }
      build(s.length, '');
      return res;
    
      function build(idx, suffix) {
        if (!idx) return res.push(suffix);
        from[idx].forEach(function(from) {
          build(from, suffix === '' ? s.substring(from, idx) : s.substring(from, idx) + ' ' + suffix);
        })
      }
    };

Log in to reply
 

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