LeetCode87. Scramble String(遞推、剪枝)(每日一題——2019.3.31)

蘇州大學大三考研狗,保研也不穩,水橋杯還要國賽,日常更新博客,不出意外每天更新一題LeetCode hard難度


題意:給一二叉樹,對於非葉子節點可以交換左右孩子結點,從而形成了新的樹,繼而每個結點代表的字符串打亂順序,問你給你兩個字符串s1與s2,問s2是否可以由s1做上述操作得到。

Below is one possible representation of s1 = "great":

    great
   /    \
  gr    eat
 / \    /  \
g   r  e   at
           / \
          a   t

To scramble the string, we may choose any non-leaf node and swap its two children.

For example, if we choose the node "gr" and swap its two children, it produces a scrambled string "rgeat".

    rgeat
   /    \
  rg    eat
 / \    /  \
r   g  e   at
           / \
          a   t

We say that "rgeat" is a scrambled string of "great".

思路:首先,既然是二叉樹,那麼一分爲二的過程中,左結點與右結點應該是擁有自此之後不變的字符種類與數量的,我們需要做的是找到這樣的分界點,然後判斷當前深度左右結點是否滿足種類與個數不變的原則。至於遍歷深度,用遞推即可,這裏需要注意的是要剪枝,不然遞推層數過多會tle。

AC code:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

class Solution
{
public:
    bool isScramble(string s1, string s2)
    {
        //特判
        if(s1.size()!=s2.size())
            return false;
        if(s1==s2)
            return true;
        vector<int>cnt(30,0);
        for(auto i:s1)
            cnt[i-'a']++;
        for(auto i:s2)
            cnt[i-'a']--;
        //剪枝
        for(int i=0;i<26;i++)
            if(cnt[i]!=0)
                return false;
        //遞歸
        for(int i=1;i<s1.size();i++)
            if( (isScramble(s1.substr(0,i),s2.substr(0,i)) && isScramble(s1.substr(i,s1.size()-i),s2.substr(i,s1.size()-i)))
             || (isScramble(s1.substr(0,i),s2.substr(s1.size()-i)) && isScramble(s1.substr(i),s2.substr(0,s1.size()-i))) )
                return true;
        return false;
    }
};

int main()
{
    string s1,s2;
    cin>>s1>>s2;
    Solution tmp;
    cout<<tmp.isScramble(s1,s2)<<endl;
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章