题目如下:
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:
时间: 2024-08-03 00:18:26