Combination Sum II
#coding=utf-8
class Solution(object):
def combinationSum2(self, candidates, target):
"""
:type candidates: List[int]
:type target: int
:rtype: List[List[int]]
"""
res=[]
for i in range(len(candidates)):
self.solution(candidates,target-candidates[i],i,[candidates[i]],res)
return res
def solution(self,nums,target,index,path,res):
if target<0:
return
if target==0:
path.sort()
if path not in res:
res.append(path)
return
for i in range(index+1,len(nums)):
self.solution(nums,target-nums[i],i,path+[nums[i]],res)
First Missing Positive
。。。感谢python的强力
#coding=utf-8
class Solution(object):
def firstMissingPositive(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
i=1
while True:
if i not in nums:
return i
i+=1
正整数0位置应该是1,1位置是2,依次向下,所以当数组中出现的正数,把它对应的下标的值改为负,根据下标判断哪里是缺少的。
class Solution:
# @param A, a list of integers
# @return an integer
# @a very subtle solution
def firstMissingPositive(self, A):
n=len(A)
for i in range(n):
if A[i]<=0: A[i]=n+2
for i in range(n):
if abs(A[i])<=n:
curr=abs(A[i])-1
A[curr]=-abs(A[curr])
for i in range(n):
if A[i]>0: return i+1
return n+1
Trapping Rain Water
一个数组记录i左边最大的,再根据i右边最大的,计算i等接多少水
#coding=utf-8
class Solution(object):
def trap(self, height):
"""
:type height: List[int]
:rtype: int
"""
if len(height)<3:
return 0
leftmax=[]
leftmax.append(0)
m=0
for i in range(0,len(height)-1):
if height[i]>m:
m=height[i]
leftmax.append(m)
maxright=height[-1]
res=0
print height
for i in range(len(height)-2,0,-1):
c=min(leftmax[i],maxright)-height[i]
if c>0:
res+=c
if height[i]>maxright:
maxright=height[i]
return res
Multiply Strings
因为要求不得使用任何内置的BigInteger库或直接将输入转换为整数。我这个复杂度有n^2,太高了
#coding=utf-8
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
temp=1
res=0
for i in num1[::-1]:
tmp=1
su=0
for j in num2[::-1]:
su+=int(i)*int(j)*tmp
tmp*=10
res+=su*temp
temp*=10
return str(res)