★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-fiipclvi-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Remember the story of Little Match Girl? By now, you know exactly what matchsticks the little match girl has, please find out a way you can make one square by using up all those matchsticks. You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.git
Your input will be several matchsticks the girl has, represented with their stick length. Your output will either be true or false, to represent whether you could make one square using all the matchsticks the little match girl has.github
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.
Note:app
0
to 10^9
.15
.還記得童話《賣火柴的小女孩》嗎?如今,你知道小女孩有多少根火柴,請找出一種能使用全部火柴拼成一個正方形的方法。不能折斷火柴,能夠把火柴鏈接起來,而且每根火柴都要用到。ide
輸入爲小女孩擁有火柴的數目,每根火柴用其長度表示。輸出即爲是否能用全部的火柴拼成正方形。spa
示例 1:code
輸入: [1,1,2,2,2] 輸出: true 解釋: 能拼成一個邊長爲2的正方形,每邊兩根火柴。
示例 2:orm
輸入: [3,3,3,3,4] 輸出: false 解釋: 不能用全部火柴拼成一個正方形。
注意:
0
到 10^9
之間。1 class Solution { 2 func makesquare(_ nums: [Int]) -> Bool { 3 if nums.isEmpty || nums.count < 4 {return false} 4 var sum:Int = nums.reduce(0, +) 5 if sum % 4 != 0 {return false} 6 var n:Int = nums.count 7 var all:Int = (1 << n) - 1 8 var target:Int = sum / 4 9 var masks:[Int] = [Int]() 10 var validHalf:[Bool] = [Bool](repeating:false,count:1 << n) 11 for i in 0...all 12 { 13 var curSum:Int = 0 14 for j in 0...15 15 { 16 if ((i >> j) & 1) == 1 17 { 18 curSum += nums[j] 19 } 20 } 21 if curSum == target 22 { 23 for mask in masks 24 { 25 if (mask & i) != 0 {continue} 26 var half:Int = mask | i 27 validHalf[half] = true 28 if validHalf[all ^ half] {return true} 29 } 30 masks.append(i) 31 } 32 } 33 return false 34 } 35 }
1 class Solution { 2 func makesquare(_ nums: [Int]) -> Bool { 3 guard nums.count >= 4 else { return false } 4 let sum = nums.reduce(0, { $0 + $1 }) 5 if sum % 4 != 0 { 6 return false 7 } 8 var sides: [Int] = Array(repeating: 0, count: 4) 9 return dfs(nums.sorted(by: >), 0, &sides, sum / 4) 10 } 11 12 func dfs(_ nums: [Int], _ index: Int, _ sides: inout [Int], _ target: Int) -> Bool { 13 if index == nums.count { 14 return sides[0] == sides[1] && sides[0] == sides[2] && sides[0] == sides[3] && sides[0] == target 15 } 16 17 for i in 0 ..< sides.count { 18 if sides[i] + nums[index] > target { 19 continue 20 } 21 sides[i] += nums[index] 22 if dfs(nums, index + 1, &sides, target) { 23 return true 24 } 25 sides[i] -= nums[index] 26 } 27 return false 28 } 29 }