回文链表
请判断一个链表是否为回文链表。
链接:https://leetcode-cn.com/problems/palindrome-linked-list/
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def isPalindrome(self, head: ListNode) -> bool:
a=[]
while head:
a.append(head.val)
head=head.next
if a==a[::-1]:
return True
return False
#也可以转换为数字或者字符串判断
有效的括号
给定一个只包括 ‘(’,’)’,’{’,’}’,’[’,’]’ 的字符串,判断字符串是否有效。
有效字符串需满足:
左括号必须用相同类型的右括号闭合。
左括号必须以正确的顺序闭合。
注意空字符串可被认为是有效字符串。
链接:https://leetcode-cn.com/problems/valid-parentheses
class Solution:
def isValid(self, s: str) -> bool:
a=[]
dic={')':'(',']':'[','}':'{'}
for i in s:
if i in ['(','[','{']:
a.append(i)
else:
if len(a)!=0 and dic[i]==a[-1]:
a.pop()
else:
return False
if len(a)==0:
return True
else:
return False
子集
给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
说明:解集不能包含重复的子集。
链接:https://leetcode-cn.com/problems/subsets/
class Solution:
def subsets(self, nums: List[int]) -> List[List[int]]:
a=[[]]
for i in range(len(nums)-1,-1,-1):
for res in a[:]:
a.append(res+[nums[i]])
return a
全排列
给定一个 没有重复 数字的序列,返回其所有可能的全排列。
链接:https://leetcode-cn.com/problems/permutations/
class Solution:
def permute(self, nums: List[int]) -> List[List[int]]:
res = []
def backtrack(nums, tmp):
if not nums:
res.append(tmp)
return
for i in range(len(nums)):
backtrack(nums[:i] + nums[i+1:], tmp + [nums[i]])
backtrack(nums, [])
return res
括号生成
数字 n 代表生成括号的对数,请你设计一个函数,用于能够生成所有可能的并且 有效的 括号组合。
链接:https://leetcode-cn.com/problems/generate-parentheses/
class Solution:
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return [""]
elif n == 1:
return ["()"]
elif n == 2:
return ["()()", "(())"]
result = []
for i in range(n):
j = n - 1 - i
temp1 = self.generateParenthesis(i)
temp2 = self.generateParenthesis(j)
result.extend(["(%s)%s" % (p, q) for p in temp1 for q in temp2])
return result