标签:star dict const pos dog bre 深度 算法 img
题目如下:
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"].
思路:用数组构造一个hashmap,用数组模拟栈模型, 用栈模型实现dps(深度优先算法)。
核心代码:
function solve(start){
var childMap=map[hash(start)];
var childMapLength=childMap.length;
for(var i=0;i<childMapLength;i++){
stack.push(childMap[i]);
if(childMap[i].finish===s.length){ //正确答案
answer.push(stringify(stack))
}else{
solve(childMap[i].finish); //递归
}
stack.pop();
}
}
solve(0);
测试结果
dict:
s=“abcdefghijk”
result:
leetcode算法 - Word Break II js实现
标签:star dict const pos dog bre 深度 算法 img
原文地址:http://www.cnblogs.com/sha256/p/6940880.html