473. Matchsticks to Square

复制代码
package LeetCode_473

/**
 * 473. Matchsticks to Square
 *https://leetcode.com/problems/matchsticks-to-square/
 * You are given an integer array matchsticks where matchsticks[i] is the length of the ith matchstick.
 * You want to use all the matchsticks to make one square.
 * You should not break any stick, but you can link them up, and each matchstick must be used exactly one time.
Return true if you can make this square and false otherwise.

Example 1:
Input: matchsticks = [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: matchsticks = [3,3,3,3,4]
Output: false
Explanation: You cannot find a way to form a square with all the matchsticks.

Constraints:
1. 1 <= matchsticks.length <= 15
2. 1 <= matchsticks[i] <= 10^8
 * */
class Solution {
    /*
    * solution: DFS, check each side's sum if equals to target, that's mean we find out the subsequence which the sum if can divided by 4
    * Time complexity: O(2^n), Space: O(2^n)
    * */
    fun makesquare(matchsticks: IntArray): Boolean {
        val sum = matchsticks.sum()
        //base checking
        if (sum % 4 != 0 || matchsticks.size < 4) {
            return false
        }
        val target = sum / 4
        //array to save the sum of every side of square
        val sideSums = IntArray(4)
        return dfs(0, target, sideSums, matchsticks)
    }

    private fun dfs(index: Int, target: Int, sideSums: IntArray, matchsticks: IntArray): Boolean {
        if (index >= matchsticks.size) {
            //check each side's sum if equals to target
            return sideSums[0] == target && sideSums[1] == target && sideSums[2] == target
        }
        //calculate the sum of 4 sides
        for (i in 0 until 4) {
            //do some pruning
            if (sideSums[i] + matchsticks[index] > target) {
                continue
            }
            sideSums[i] += matchsticks[index]
            //and check for next level
            if (dfs(index + 1, target, sideSums, matchsticks)) {
                return true
            }
            //reduce for backtracking
            sideSums[i] -= matchsticks[index]
        }
        return false
    }
}
复制代码

 

posted @   johnny_zhao  阅读(42)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示