-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create 3213.Construct-String-with-Minimum-Cost.cpp
- Loading branch information
1 parent
dfb9117
commit b0a362c
Showing
1 changed file
with
62 additions
and
0 deletions.
There are no files selected for viewing
62 changes: 62 additions & 0 deletions
62
DFS/3213.Construct-String-with-Minimum-Cost/3213.Construct-String-with-Minimum-Cost.cpp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -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(); | ||
vector<int>memo; | ||
public: | ||
int minimumCost(string target, vector<string>& words, vector<int>& costs) | ||
{ | ||
memo = vector<int>(target.size(), -1); | ||
|
||
for (int i=0; i<words.size(); i++) | ||
{ | ||
TrieNode* node = root; | ||
for (auto ch: words[i]) | ||
{ | ||
if (node->next[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; i<target.size(); i++) | ||
{ | ||
if (node->next[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; | ||
} | ||
}; |