程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> [LeetCode]Scramble String

[LeetCode]Scramble String

編輯:C++入門知識

class Solution {  
//O(n^4) DP with some cut off can pass the large judge  
//O(n^2) recursion with some cut off can also pass the large judge   
public:  
    bool isScramble(string s1, string s2) {  
        // Start typing your C/C++ solution below  
        // DO NOT write int main() function  
        if(s1.size() != s2.size()) return false;  
        int n = s1.size();  
        if(n == 0) return true;  
        vector<vector<vector<bool> > > f(n, vector<vector<bool> >(n, vector<bool>(n+1, false)));  
        //initialize  
        for(int i = 0; i < n; ++i)  
        {  
            for(int j = 0; j < n; ++j)  
            {  
                if(s1[i] == s2[j]) f[i][j][1] = true;  
            }  
        }  
        //dp  
        for(int len = 2; len <= n; ++len)  
        {  
            for(int i = 0; i < n; ++i)  
            {  
                if(i+len-1 >= n) break;  
                for(int j = 0; j < n; ++j)  
                {  
                    if(j+len-1 >= n) break;  
                    for(int k = 1; k < len; ++k)  
                    {  
                        if(i+k < n && j+k < n) f[i][j][len] = f[i][j][len] || (f[i][j][k] && f[i+k][j+k][len-k]);  
                        if(j+len-k < n && i+k < n) f[i][j][len] = f[i][j][len] || (f[i][j+len-k][k] && f[i+k][j][len-k]);  
                        if(f[i][j][len] == true) break;  
                    }  
                }  
            }  
        }  
        return f[0][0][n];  
    }  
};  

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved