classSolution{ fun wordBreak(s: String, wordDict: List<String>): List<String> { if (s.isEmpty()) return emptyList() return dfs(s, wordDict.toSet(), 0) }
val map = HashMap<Int, List<String>>()
fun dfs(s: String, wordDict: Set<String>, start: Int): List<String> { if (start == s.length) return emptyList() if (map.containsKey(start)) return map[start]!! val res = mutableListOf<String>() for (i in start until s.length) { val subString = s.substring(start, i + 1) if (!wordDict.contains(subString)) continue if (i + 1 == s.length) { res.add(subString) // 找到最后一段时直接跳出循环 continue } val list = dfs(s, wordDict, i + 1) for (string in list) res.add("$subString $string") } map[start] = res return res } }