Skip to content

Commit 6e17580

Browse files
authored
Create 2002.Maximum-Product-of-the-Length-of-Two-Palindromic-Subsequences.cpp
1 parent 282dbca commit 6e17580

1 file changed

Lines changed: 60 additions & 0 deletions

File tree

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
class Solution {
2+
int dp[1<<12];
3+
unordered_map<int,int>memo;
4+
public:
5+
bool isPalin(string&s, int state)
6+
{
7+
if (memo.find(state)!=memo.end())
8+
return memo[state];
9+
10+
vector<int>idx;
11+
int n = s.size();
12+
for (int i=0; i<n; i++)
13+
{
14+
if ((state>>i)&1)
15+
idx.push_back(n-1-i);
16+
}
17+
reverse(idx.begin(), idx.end());
18+
19+
int i=0, j=idx.size()-1;
20+
while (i<j)
21+
{
22+
if (s[idx[i]]!=s[idx[j]])
23+
{
24+
memo[state]=0;
25+
return false;
26+
}
27+
i++;
28+
j--;
29+
}
30+
memo[state]=1;
31+
return true;
32+
}
33+
34+
35+
int maxProduct(string s)
36+
{
37+
int n = s.size();
38+
39+
for (int state=1; state<(1<<n); state++)
40+
{
41+
int t = __builtin_popcount(state);
42+
if (isPalin(s, state))
43+
{
44+
dp[state] = t;
45+
continue;
46+
}
47+
for (int i=0; i<n; i++)
48+
{
49+
if ((state>>i)&1)
50+
dp[state] = max(dp[state], dp[state-(1<<i)]);
51+
}
52+
}
53+
54+
int all = (1<<n)-1;
55+
int ret = 0;
56+
for (int subset=1; subset<(1<<n); subset++)
57+
ret = max(ret, dp[all-subset]*dp[subset]);
58+
return ret;
59+
}
60+
};

0 commit comments

Comments
 (0)