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
        }
    }
  • 相关阅读:
    task打印执行结果
    九宫格----记网易游戏2015年研发类笔试题
    第一篇博客
    http超时机制
    SVN错误解决办法
    FFmpeg源码编译
    闲来无事——第一弹 Java基础 基本数据类型
    一个比较好的图标搜索网站
    JS 跑马灯
    Jquery
  • 原文地址:https://www.cnblogs.com/johnnyzhao/p/15140737.html
Copyright © 2011-2022 走看看