关于括号匹配或生成的问题,首先想到的是栈. 本题易错点:返回值为连续有效()的长度, 即()(()这种情况下,返回值为2 # 去除字符串首的连续)和字符串尾得连续( while True: if not s or len(s)==1:return 0 if s[0]==')':s= s[1:] if s[-1] =='(':s=s[:-1] else:break res = 0 # 定义栈 stack = [-1] for i in range(len(s)): # 为(时,将索引压入栈中 if…
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: "((()))", "(()())", "(())()", "()(())", "()()()" 在LeetCo…
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. The brackets must close in the correct order, "()" and "()[]{}" are all valid but "(]" and "([)]"…
Given a balanced parentheses string S, compute the score of the string based on the following rule: () has score 1 AB has score A + B, where A and B are balanced parentheses strings. (A) has score 2 * A, where A is a balanced parentheses string. Exam…
Given a string containing just the characters'(',')','{','}','['and']', determine if the input string is valid. The brackets must close in the correct order,"()"and"()[]{}"are all valid but"(]"and"([)]"are not. 题意:给…
引言 一维动态规划根据转移方程,复杂度一般有两种情况. func(i) 只和 func(i-1)有关,时间复杂度是O(n),这种情况下空间复杂度往往可以优化为O(1) func(i) 和 func(1~i-1)有关,时间复杂度是O(n*n),这种情况下空间复杂度一般无法优化,依然为O(n) 本篇讨论第一种情况 例题 1 Jump Game Given an array of non-negative integers, you are initially positioned at the fi…
思路: 首先用字典将三对括号存储,遍历字符串中每个字符,遇到左括号就入栈:遇到右括号就开始判断:是否与栈弹出的顶字符相同. 如果到最后栈被清空,说明全部匹配上了,为真. class Solution(object): def isValid(self, s): stack=[] #设置一个列表,把该列表当做栈来使用即可 dic={'(':')','{':'}','[':']'} #使用字典存储括号 new_dic = {v : k for k, v in dic.items()} #由于不能直接…
Array: Single Number class Solution { public int singleNumber(int[] nums) { if (nums == null || nums.length == 0) { return 0; } int res = nums[0]; for (int i = 1; i < nums.length; i++) { res = res ^ nums[i]; } return res; } } Remove Duplicates from S…
引言 二维动态规划中最常见的是棋盘型二维动态规划. 即 func(i, j) 往往只和 func(i-1, j-1), func(i-1, j) 以及 func(i, j-1) 有关 这种情况下,时间复杂度 O(n*n),空间复杂度往往可以优化为O(n) 例题 1 Minimum Path Sum Given a m x n grid filled with non-negative numbers, find a path from top left to bottom right whi…
Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses. For example, given n = 3, a solution set is: [ "((()))", "(()())", "(())()", "()(())", "()()()" ] 根据题…