#16
3Sum Closest
Example:
Given array nums = [-1, 2, 1, -4], and target = 1. The sum that is closest to the target is 2. (-1 + 2 + 1 = 2).
解题方法:直接暴力枚举,若刚好找到三个数的和等于target,结束。否则,记录最优解。
class Solution:
def threeSumClosest(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype
"""
nums.sort()
diff_min = 1000000
total = 0
for i in range(len(nums)):
start = i + 1
end = len(nums) - 1
while start < end:
sum = nums[i] + nums[start] + nums[end]
diff = sum - target
if diff == 0:
return sum
elif diff > 0:
if abs(diff) < diff_min:
diff_min = diff
total = sum
end -= 1
else:
if abs(diff) < diff_min:
diff_min = abs(diff)
total = sum
start += 1
return total
#62,
Unique Paths
A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3 Output: 28
解题方法:采用数学的方法,注意到robot要到右下方,必须向下走m-1步,向右走n-1步。寻找不同路径的数目实际上是一个排列组合问题。该问题转化为:
有m+n-2个球,其中m-1个球为白色,n-1个球为黑色,所有球除颜色外均一模一样。求这m+n-2个球有多少种排列方法。
答案为 (m+n-2)C(n-1)种方法,将这个式子转化为代码即可。
class Solution:
def uniquePaths(self, m, n):
"""
:type m: int
:type n: int
:rtype: int
"""
if n == 1:
return 1
elif m == 1:
return 1
return int(self.part_factorial(m+n-2, n-1) / self.part_factorial(n-1, n-1))
def part_factorial(self, num, amount):
total = num
for i in range(amount-1):
num -= 1
total *= num
return total