标签:
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses (
and )
.
Examples:
"()())()" -> ["()()()", "(())()"] "(a)())()" -> ["(a)()()", "(a())()"] ")(" -> [""]https://leetcode.com/problems/remove-invalid-parentheses/
dfs(str.substring(1), subRes + ‘(‘, countLeft + 1, maxLeft + 1);
dfs(str.substring(1), subRes, countLeft, maxLeft);
保证了匹配括号多的结果一定会先出现在结果数组中,不会遗漏结果。
https://leetcode.com/discuss/68272/straight-forward-solution-with-explanation
1 /** 2 * @param {string} s 3 * @return {string[]} 4 */ 5 var removeInvalidParentheses = function(s) { 6 var res = [], max = 0; 7 dfs(s, "", 0, 0); 8 return res.length !== 0 ? res : [""]; 9 10 function dfs(str, subRes, countLeft, maxLeft){ 11 if(str === ""){ 12 if(countLeft === 0 && subRes !== ""){ 13 if(maxLeft > max) 14 max = maxLeft; 15 if(max === maxLeft && res.indexOf(subRes) === -1) 16 res.push(subRes); 17 } 18 return; 19 } 20 if(str[0] === ‘(‘){ 21 dfs(str.substring(1), subRes + ‘(‘, countLeft + 1, maxLeft + 1); 22 dfs(str.substring(1), subRes, countLeft, maxLeft); 23 }else if(str[0] === ‘)‘){ 24 if(countLeft > 0) 25 dfs(str.substring(1), subRes + ‘)‘, countLeft - 1, maxLeft); 26 dfs(str.substring(1), subRes, countLeft, maxLeft); 27 }else{ 28 dfs(str.substring(1), subRes + str[0], countLeft, maxLeft); 29 } 30 } 31 };
[LeetCode][JavaScript]Remove Invalid Parentheses
标签:
原文地址:http://www.cnblogs.com/Liok3187/p/4946376.html