Leetcode "word break"

Source: Internet
Author: User

My first solution was DFS-tle. Apparently, DFS with TLE usually means DP.

1D DP + rolling array:

class Solution {public:    bool wordBreak(string s, unordered_set<string> &dict) {        int len = s.length();        int lend= dict.size();        if(len == 0 || lend == 0) return false;                //    Init        vector<bool> rec0, rec1;        rec0.resize(len); rec1.resize(len);        std::fill(rec0.begin(), rec0.end(), false);        std::fill(rec1.begin(), rec1.end(), false);        //        vector<bool> &pre = rec0;        vector<bool> &post = rec1;        //    Start from 0        for(int i = 1; i <= len; i ++)        {            string sub = s.substr(0, i);            if(dict.find(sub) != dict.end())            {                pre[i-1] = true;                if(i == len) return true;            }        }        for(int i = 1; i < len; i ++)    // vertical        {            for(int j = 0; j < len; j ++)    // horizontal            {                if(pre[j])                {                    for(int k = 1; k < len - j; k ++)                    {                        string sub = s.substr(j + 1, k);                        if(dict.find(sub) != dict.end())                        {                            post[j + k] = true;                            if((j + k + 1) == len) return true;                        }                    }                }            }            //    Rolling array            if(i % 2)            {                pre = rec1; post = rec0;            }            else            {                pre = rec0; post = rec1;            }        }        return false;    }};

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.