leetcode473. Matchsticks to Square★
阿新 • • 發佈:2018-12-15
總結 可以2sum,3sum, 4sum…頭暈 - Mark程式碼不是最簡的,待完善
題目描述
給定一些整數,代表火柴棍的長度。求這些火柴棍是否可以組成一個正方形。火柴棍不可以拆分,但是可以拼接。
例子 Example 1:
Input: [1,1,2,2,2] Output: true
Explanation: You can form a square with length 2, one side of the square came two sticks with length 1. Example 2:
Input: [3,3,3,3,4] Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.
解法 很容易得到正方形的邊長side; 建立一個長度為4的輔助陣列subNums表示4條邊的邊長; (截止條件) 前三條邊長度都等於side,返回True (主體) 嘗試填充四條邊,如果填充完了都無法返回True,則返回False (剪枝):陣列nums排序-O(nlogn);從大數開始操作,節省時間
解法 DFS
class Solution(object):
def makesquare(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
side = sum(nums) / 4
if len(nums) < 4 or max(nums) > side or side * 4 != sum(nums):
return False
nums.sort(reverse = True)
subNums = [side] * 4
return self.dfs(nums, subNums, side, 0)
def dfs(self, nums, subNums, side, idx):
if idx == len(nums):
return True
num = nums[idx]
for i in range(4):
if subNums[i] >= num:
subNums[i] -= num
if self.dfs(nums, subNums, side, idx+1):
return True
subNums[i] += num
return False