1239. Maximum Length of a Concatenated String with Unique Characters
Given an array of strings arr
. String s
is a concatenation of a sub-sequence of arr
which have unique characters.
Return the maximum possible length of s
.
Example 1:
Input: arr = ["un","iq","ue"]
Output: 4
Explanation: All possible concatenations are "","un","iq","ue","uniq" and "ique".
Maximum length is 4.
Example 2:
Input: arr = ["cha","r","act","ers"]
Output: 6
Explanation: Possible solutions are "chaers" and "acters".
Example 3:
Input: arr = ["abcdefghijklmnopqrstuvwxyz"]
Output: 26
Constraints:
1 <= arr.length <= 16
1 <= arr[i].length <= 26
arr[i]
contains only lower case English letters.
题目:给定一个字符串数组 arr
,字符串 s
是将 arr
某一子序列字符串连接所得的字符串,如果 s
中的每一个字符都只出现过一次,那么它就是一个可行解。请返回所有可行解 s
中最长长度。
思路:DFS,组合问题。
【TLE】
class Solution {
public:
int maxLength(vector<string>& arr) {
int res = 0;
helper(arr, "", res, 0);
return res;
}
private:
void helper(const vector<string>& arr, string seen, int& res, int start){
if(start == arr.size())
return;
for(int i = start; i < arr.size(); ++i){
bool unique = true;
// 判断某个字符串中是否有重复的字符,"aaa"
set<char> st(arr[i].begin(), arr[i].end());
if(st.size() != arr[i].size())
continue;
// 判断该字符串是否和seen中的字符串有重复的字符
for(auto c : arr[i]){
if(seen.find(c) != std::string::npos){
unique = false;
break;
}
}
if(unique){
helper(arr, seen+arr[i], res, i+1);
res = max(res, (int)arr[i].size() + (int)seen.size());
}
else{
helper(arr, seen, res, i+1);
}
}
return;
}
};
class Solution {
public:
int maxLength(vector<string>& arr) {
int res = 0;
bitset<26> b;
helper(arr, b, res, 0);
return res;
}
private:
void helper(const vector<string>& arr, bitset<26> b, int& res, int start){
if(start == arr.size())
return;
for(int i = start; i < arr.size(); ++i){
bitset<26> a;
string s = arr[i];
for(auto c : s)
a.set(c - 'a');
int n = a.count();
if(n != s.size())
continue;
if((a & b).any())
helper(arr, b, res, i + 1);
else
{
res = max(res, (int)b.count() + n);
helper(arr, b | a, res, i + 1);
}
}
return;
}
};