leetcode 691. Stickers to Spell Word(状压dp)

来源:互联网 发布:pc围棋软件 编辑:程序博客网 时间:2024/06/07 10:44

题目:https://leetcode.com/contest/leetcode-weekly-contest-53/problems/stickers-to-spell-word/#
题意:给你n个stickers串,然后让你拼出target串(所谓拼出,就是删除一些字符后重组成target),让求拼出target的最小stickers数目
思路:状压dp
代码:

#include<bits/stdc++.h>using namespace std;#define ms1(X) memset((X), -1, sizeof((X)))#define SZ(X) ((int)(X).size())int dp[1<<16];class Solution {public:    int minStickers(vector<string>& s, string t) {        int m = SZ(t);        ms1(dp);        dp[0] = 0;        for(int st = 0;st < (1<<m);st++){            if(dp[st] == -1) continue;            for(int i = 0;i < s.size();i++){                int now = st;                for(int j = 0;j < s[i].size();j++){                    for(int k = 0;k < m;k++){                        if(((now >> k) & 1) == 1) continue;                        if(t[k] == s[i][j]){                            now |= 1<<k;                            break;                        }                    }                }                if(dp[now] == -1 || dp[now] > dp[st] + 1)                    dp[now] = dp[st] + 1;            }        }        return dp[(1<<m)-1];    }};
原创粉丝点击