1790. Most Unique Pieces
A printer has to cut a long ribbon of letters, written as the string s, into labelled strips. Every strip is a non-empty run of consecutive letters, the strips together use every letter of s exactly once and in order, and no two strips may spell the same text.
Return the largest number of strips you can obtain. The answer is always at least 1, because the whole string is one valid strip. Backtrack over the cut positions while keeping a set of strips already used; prune a branch as soon as the strips chosen so far plus the letters still unused cannot exceed the best count found. Only the count is returned, so ties between different cuttings do not matter. With n = s.length at most 16 the search is exponential in n; space is O(n) for the recursion and the set.
Example 1
- Input:
- s = "ababccc"
- Output:
- 5
- Explanation:
Cut as a|b|ab|c|cc, five pieces that are all different; no cutting gives six, so the answer is 5.
Example 2
- Input:
- s = "aaa"
- Output:
- 2
- Explanation:
Cut as a|aa, the only way to keep both pieces different, so the answer is 2.
Example 3
- Input:
- s = "abcd"
- Output:
- 4
- Explanation:
Every letter can be its own piece, so the answer is 4.
Constraints
1 ≤ s.length ≤ 16
s consists of lowercase English letters
How this problem is judged
- Answers
- Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
- Time per case
- Python 2,000 msC++ 500 msJava 1,000 msJavaScript 1,000 msTypeScript 1,000 ms
Expected complexity
- Time
- O(2^n) with pruning
- Space
- O(n)