标签:
DFS with pruning. The thought flow: for each char, we have 2 choices: pick or not - then DFS.
class Solution { int len; unordered_set<string> rec; vector<string> ret; void go(const string &s, int i, string picked, int cl, int cr) { // prune if(cl < cr) return; if((cl - cr) > s.length()) return; if((picked.length() + s.length() - i) < len) return; if(i == s.length()) { if(cl == cr) { auto clen = picked.length(); if(clen >= len) { if(clen > len) { len = clen; rec.clear(); ret.clear(); } if(!rec.count(picked)) { rec.insert(picked); ret.push_back(picked); } } } return; } go(s, i + 1, picked, cl, cr); // drop char c = s[i]; int ncl = cl, ncr = cr; if(c == ‘(‘) ncl ++; else if (c == ‘)‘) ncr ++; go(s, i + 1, picked + c, ncl, ncr); // pick } public: vector<string> removeInvalidParentheses(string s) { len = 0; go(s, 0, "", 0, 0); return ret; } };
LeetCode "Remove Invalid Parentheses"
标签:
原文地址:http://www.cnblogs.com/tonix/p/4938097.html