zoukankan      html  css  js  c++  java
  • b_lc_两个回文子序列长度的最大乘积(间隔 dfs / 状压)

    找到 s 中两个 不相交回文子序列 ,使得它们长度的 乘积最大 。两个子序列在原字符串中如果没有任何相同下标的字符,则它们是 不相交 的。n<10

    思路:不相交,就直接在dfs的时候控制他们不能选同一个字符就行了

    class Solution {
    public:
        int ans;
        bool chk(string& s) {
            for (int i = 0; i < s.size() / 2; i++) {
                if (s[i] != s[s.size()-i-1]) {
                    return false;
                }
            }
            return true;
        }
        void dfs(int i, string a, string b, string& s) {
            if (i >= s.size()) {
                if (chk(a) && chk(b)) {
                    ans = max(ans, int(a.size() * b.size()));
                }
                return;
            }
            dfs(i+1, a+s[i], b, s);
            dfs(i+1, a, b, s);
            dfs(i+1, a, b+s[i], s);
        }
        int maxProduct(string s) {
            dfs(0, "", "", s);
            return ans;
        }
    };
    

    不过有点暴力...

    class Solution {
    public:
        int maxProduct(string s) {
            int tot = 1 << s.size();
    
            vector<pair<int, int>> A;
            for (int i = 1; i < tot; ++i) {
                string t;
                for (int j = 0; j < s.size(); ++j) {
                    if (i & (1 << j)) {
                        t += s[j];
                    }
                }
                string tt = t;
                reverse(tt.begin(), tt.end());
                if (t == tt)
                    A.push_back({t.size(), i});
            }
    
            int ans = 0;
            for (int i = 0; i < A.size(); ++i) {
                for (int j = i + 1; j < A.size(); ++j) {
                    if ((A[i].second & A[j].second) == 0) {
                        ans = max(ans, int(A[i].first * A[j].first));
                    }
                }
            }
            return ans;
        }
    };
    
  • 相关阅读:
    对于delphi 三层的理解
    XE6调用android标准功能
    修复 XE7 Frame 内 PopupMenu 快捷键失效问题 by 龟山阿卍
    最大熵模型 二
    最大熵模型
    算法复习-平面内极大值点
    算法复习-生成全排列
    算法复习-归并排序
    算法复习-快速排序
    连续特征的离散化
  • 原文地址:https://www.cnblogs.com/wdt1/p/15257790.html
Copyright © 2011-2022 走看看