Approach
Depth-first search
For Find the Shortest Superstring, the implementation follows one branch at a time, making it suitable for components, trees, backtracking, or dependency exploration.
- Define the state carried into one recursive or stack frame.
- Mark or choose the current state before exploring children.
- Combine child results or undo the choice when the branch finishes.
Code notes
- 69 lines of Java from the credited upstream file 943.java.
- The implementation visibly relies on sequence storage.
- 6 loop blocks detected, together with recursive traversal.
Complexity
Count unique states for graph traversal; for backtracking, count the branching factor and maximum depth.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class Solution {2 public String shortestSuperstring(String[] words) {3 final int n = words.length;4 5 int[][] cost = new int[n][n];6 7 8 for (int i = 0; i < n; ++i)9 for (int j = i + 1; j < n; ++j) {10 cost[i][j] = getCost(words[i], words[j]);11 cost[j][i] = getCost(words[j], words[i]);12 }13 14 List<Integer> path = new ArrayList<>();15 List<Integer> bestPath = new ArrayList<>();16 17 minLength = n * 20; 18 19 dfs(words, cost, path, bestPath, 0, 0, 0);20 21 StringBuilder sb = new StringBuilder(words[bestPath.get(0)]);22 23 for (int k = 1; k < n; ++k) {24 final int i = bestPath.get(k - 1);25 final int j = bestPath.get(k);26 sb.append(words[j].substring(words[j].length() - cost[i][j]));27 }28 29 return sb.toString();30 }31 32 private int minLength;33 34 35 private int getCost(final String a, final String b) {36 int cost = b.length();37 final int minLength = Math.min(a.length(), b.length());38 for (int k = 1; k <= minLength; ++k)39 if (a.substring(a.length() - k).equals(b.substring(0, k)))40 cost = b.length() - k;41 return cost;42 }43 44 45 private void dfs(String[] words, int[][] cost, List<Integer> path, List<Integer> bestPath,46 int used, int depth, int currLength) {47 if (currLength >= minLength)48 return;49 if (depth == words.length) {50 minLength = currLength;51 bestPath.clear();52 for (final int node : path) {53 bestPath.add(node);54 }55 return;56 }57 58 for (int i = 0; i < words.length; ++i) {59 if ((used >> i & 1) == 1)60 continue;61 path.add(i);62 final int newLength =63 depth == 0 ? words[i].length() : currLength + cost[path.get(depth - 1)][i];64 dfs(words, cost, path, bestPath, used | 1 << i, depth + 1, newLength);65 path.remove(path.size() - 1);66 }67 }68}69