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
        }
    }
  • 相关阅读:
    HTML基础02
    HTML基础01
    【springboot中的常用注解】
    【git常用命令】
    【spring使用@Async注解异步处理】
    【let definitions are not supported by current javascript】
    【sql update if else】
    【Tomcat运行时异常:Illegal access: this web application instance has been stopped already.】
    【JAVA float double数据类型保留2位小数点5种方法】
    【MyBatis中大于号以及小于号的表达方式】
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15140737.html
Copyright © 2011-2022 走看看