思路:
状压dp。
实现:
1 #include <bits/stdc++.h> 2 using namespace std; 3 class Solution 4 { 5 public: 6 int minStickers(vector<string>& stickers, string target) 7 { 8 vector<vector<int>> v(stickers.size(), vector<int>(26, 0)); 9 for (int i = 0; i < stickers.size(); i++) 10 { 11 for (int j = 0; j < stickers[i].size(); j++) 12 { 13 v[i][stickers[i][j] - 'a']++; 14 } 15 } 16 vector<int> dp(1 << target.size(), -1); 17 int ret = dfs(0, v, target, dp); 18 if (ret < 0x3f3f3f3f) return ret; 19 return -1; 20 } 21 int dfs(int now, vector<vector<int>>& v, string target, vector<int>& dp) 22 { 23 if (now == (1 << target.size()) - 1) return 0; 24 if (dp[now] != -1) return dp[now]; 25 int minn = 0x3f3f3f3f; 26 27 for (int i = 0; i < v.size(); i++) 28 { 29 vector<int> tmp = v[i]; 30 int s = now; 31 for (int j = 0; j < target.size(); j++) 32 { 33 if (!(s & (1 << j)) && tmp[target[j] - 'a']) 34 { 35 s |= (1 << j); tmp[target[j] - 'a']--; 36 } 37 } 38 if (s != now) { minn = min(minn, dfs(s, v, target, dp) + 1); } 39 } 40 return dp[now] = minn; 41 } 42 };