Guest User

Untitled

a guest
Mar 24th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.47 KB | None | 0 0
  1. class Solution {
  2. public:
  3. int minStickers(vector<string>& stickers, string target) {
  4. int n = target.size(), len = stickers.size();
  5. //dp represents minimum sticker required for current state
  6. //state is a binary number where each bit represents if corresponding char appears
  7. vector<int> dp(1 << n, n + 1);
  8. dp[0] = 0;
  9. for(int i = 1; i < 1 << n; ++i)
  10. {
  11. for(auto sticker : stickers)
  12. {
  13. int state = 0;
  14. for(int j = 0; j < sticker.size(); ++j)
  15. {
  16. for(int k = 0; k < n; ++k)
  17. {
  18. //if we have two same chars, two 'a's
  19. //if the first 'a' is matched, we don't
  20. //want the second 'a' to match the same
  21. //position in i again
  22. if((state >> k & 1) == 1)continue;
  23. if(i >> k & 1 && sticker[j] == target[k])
  24. {
  25. //if current char c in sticker is matched
  26. //it shouldn't match another char in i again,
  27. //we just break
  28. state |= 1 << k;
  29. break;
  30. }
  31. }
  32. }
  33. dp[i] = min(dp[i], dp[i - state] + 1);
  34. }
  35. }
  36. return dp[(1 << n) - 1] == n + 1? -1: dp[(1 << n) - 1];
  37. }
  38. };
Add Comment
Please, Sign In to add comment