diff --git a/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp b/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp new file mode 100644 index 000000000..71fc75c63 --- /dev/null +++ b/DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp @@ -0,0 +1,62 @@ +class TrieNode +{ + public: + TrieNode* next[26]; + int cost; + TrieNode() + { + for (int i=0; i<26; i++) + next[i] = NULL; + cost = -1; + } +}; + +class Solution { + TrieNode* root = new TrieNode(); + vectormemo; +public: + int minimumCost(string target, vector& words, vector& costs) + { + memo = vector(target.size(), -1); + + for (int i=0; inext[ch-'a']==NULL) + node->next[ch-'a'] = new TrieNode(); + node = node->next[ch-'a']; + } + if (node->cost==-1) + node->cost = costs[i]; + else + node->cost = min(node->cost, costs[i]); + } + + int ret = dfs(target, 0); + if (ret == INT_MAX/2) return -1; + else return ret; + } + + int dfs(string& target, int cur) + { + if (cur==target.size()) return 0; + if (memo[cur] != -1) return memo[cur]; + + int ans = INT_MAX/2; + TrieNode* node = root; + for (int i=cur; inext[target[i]-'a']==NULL) + break; + node = node->next[target[i]-'a']; + if (node->cost!=-1) + ans = min(ans, node->cost + dfs(target, i+1)); + } + + memo[cur] = ans; + + return ans; + } +};