1class Solution {2List<String> res = new ArrayList<>();3String s;4int index = 0;5Set<String> set = new HashSet<>();67public List<String> wordBreak(String s, List<String> wordDict) {8this.s = s;9for (String word : wordDict) set.add(word);10backtrack("");11return res;12}1314public void backtrack(String sentence) {15if (index == s.length()) {16res.add(sentence.trim());17return;18}19int indexCopy = index;20for (int i = index + 1; i <= s.length(); i++) {21String str = s.substring(index, i);22if (set.contains(str)) {23index = i;24backtrack(sentence + " " + str);25index = indexCopy;26}27}28return;29}30}