# 691. 贴纸拼词 : DFS + 记忆化搜索 运用题

## 题目描述

Tag : 「记忆化搜索」、「DFS」、「状态压缩」、「爆搜」

输入： stickers = ["with","example","science"], target = "thehat"



输入：stickers = ["notice","possible"], target = "basicbasic"



• $n == stickers.length$
• $1 <= n <= 50$
• $1 <= stickers[i].length <= 10$
• $1 <= target <= 15$
• stickers[i] 和 target 由小写英文单词组成

## DFS + 记忆化搜索

class Solution {
int N = 20, M = 1 << 20, INF = 50;
int[] f = new int[M];
String[] ss;
String t;
int dfs(int state) {
int n = t.length();
if (state == ((1 << n) - 1)) return 0;
if (f[state] != -1) return f[state];
int ans = INF;
for (String s : ss) {
int nstate = state;
out:for (char c : s.toCharArray()) {
for (int i = 0; i < n; i++) {
if (t.charAt(i) == c && ((nstate >> i) & 1) == 0) {
nstate |= (1 << i);
continue out;
}
}
}
if (nstate != state) ans = Math.min(ans, dfs(nstate) + 1);
}
return f[state] = ans;
}
public int minStickers(String[] stickers, String target) {
ss = stickers; t = target;
Arrays.fill(f, -1);
int ans = dfs(0);
return ans == INF ? -1 : ans;
}
}

• 时间复杂度：令 $n$$m$ 分别代表字符串 t 的长度和数组 ss 的长度。共有 $2^n$ 个状态，单次状态的计算复杂度为 $O(\sum_{i = 0}^{m - 1}ss[i].length \times n)$。整体复杂度为 $O(2^n \times \sum_{i = 0}^{m - 1}ss[i].length \times n)$
• 空间复杂度：$O(2^n)$