zoukankan      html  css  js  c++  java
  • 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
        }
    }
  • 相关阅读:
    第七周编程总结
    第六周编程总结
    第五周编程总结
    2019 第四周作业编程总结
    第三周编程总结
    寒假作业 pta编程总结3
    跟着官网学Angular-创建响应式表单-源代码
    RxJS---转载
    NPM
    Sass
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15140737.html
Copyright © 2011-2022 走看看