[LeetCode]题解(python):032-Longest Valid Parentheses
题目来源:
https://leetcode.com/problems/longest-valid-parentheses/
题意分析:
返回字符串的最长括号匹配长度。
题目思路:
将左括号的位置append到一个list上面。用last来记录最后一个位置,如果遇到右括号,若此时list为空,则更新last位置。否者pop一位,如果pop后list为空,那么此时长度是右括号位置 - last位置,否者是右括号位置 - list头部。
代码(python):
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 class Solution(object): 2 def boolcombinationSum(self, candidates, target,j): 3 ans = [];size = len(candidates) 4 if target == 0: 5 return [] 6 if size < j + 1 or target < 0: 7 return [[-1]] 8 tmp1 = self.boolcombinationSum(candidates,target,j + 1);tmp2 = self.boolcombinationSum(candidates,target - candidates[j],j) 9 if len(tmp2) == 0: 10 ans.append([candidates[j]]) 11 elif tmp2 != [[-1]]: 12 for i in range(len(tmp2)): 13 ans.append([candidates[j]] + tmp2[i]) 14 if len(tmp1) != 0 and tmp1 != [[-1]]: 15 for i in range(len(tmp1)): 16 ans.append(tmp1[i]) 17 if len(tmp2) != 0 and tmp1 == [[-1]] and tmp2 == [[-1]]: 18 return [[-1]] 19 return ans 20 def combinationSum(self, candidates, target): 21 """ 22 :type candidates: List[int] 23 :type target: int 24 :rtype: List[List[int]] 25 """ 26 candidates.sort() 27 ans = self.boolcombinationSum(candidates,target,0) 28 if ans == [[-1]]: 29 return [] 30 return ans
转载请注明出处:http://www.cnblogs.com/chruny/p/4918334.html