作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/


题目地址:https://leetcode.com/problems/matchsticks-to-square/description/

题目描述

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.

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.

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:

  1. The length sum of the given matchsticks is in the range of 0 to 10^9.
  2. The length of the given matchstick array will not exceed 15.

题目大意

题目很长,讲的是卖火孩的小女柴,把火柴拼在一起能不能得到一个正方形。当然火柴是不能折断的,而且要全部都用上。

解题方法

回溯法

这个题目很长,其实就一句话:能不能把一组数字分成4组,每组的和是相同的。

我们注意到题目给出的数组长度最多只有15个,基本上可以使用O(N!)的时间复杂度去解决。所以我们可以直接使用回溯法。回溯的思路是先设置好4条边,然后把每一个火柴看看能不能放到4条边中的一个去,如果可以的话就继续向后扫描,直到所有的火柴全部用上为止。

同样使用416. Partition Equal Subset Sum的方法,也就是在使用记录四组的和的方式,进行遍历的时候保存各个组的和,如果不能满足就把这个数字再加上,相当于跳过这个数字的方式。最后结束的条件就是所有的数字全部都用完了,因为如果用完了,说明我们把所有的火柴都放到了4条边中的一个,所以得到每组都满足我们条件的结论。

Python代码:

class Solution:
def makesquare(self, nums):
"""
:type nums: List[int]
:rtype: bool
"""
if not nums or len(nums) < 4: return False
_sum = sum(nums)
div, mod = divmod(_sum, 4)
if mod != 0 or max(nums) > _sum / 4: return False
nums.sort(reverse = True)
target = [div] * 4
return self.dfs(nums, 0, target) def dfs(self, nums, index, target):
if index == len(nums): return True
num = nums[index]
for i in range(4):
if target[i] >= num:
target[i] -= num
if self.dfs(nums, index + 1, target): return True
target[i] += num
return False

C++代码如下:

class Solution {
public:
bool makesquare(vector<int>& nums) {
if (nums.size() < 4) return false;
int sum = accumulate(nums.begin(), nums.end(), 0);
if (sum % 4 != 0)
return false;
int edge = sum / 4;
vector<int> target(4, edge);
return helper(nums, 0, target);
}
bool helper(vector<int>& nums, int index, vector<int>& target) {
const int N = nums.size();
if (index == N) return true;
int num = nums[index];
for (int i = 0; i < 4; ++i) {
if (target[i] >= num) {
target[i] -= num;
if (helper(nums, index + 1, target))
return true;
target[i] += num;
}
}
return false;
}
};

日期

2018 年 4 月 2 日 —— 要开始准备ACM了
2019 年 2 月 23 日 —— 没时间了

【LeetCode】473. Matchsticks to Square 解题报告(Python & C++)的更多相关文章

  1. 【LeetCode】593. Valid Square 解题报告(Python)

    [LeetCode]593. Valid Square 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地 ...

  2. 【LeetCode】221. Maximal Square 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 动态规划 日期 题目地址: https://leet ...

  3. 【LeetCode】62. Unique Paths 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址:https://leetcode.com/problems/unique-pa ...

  4. LeetCode "473. Matchsticks to Square"

    A trickier DFS, with a little bit complex recursion param tweak, and what's more important is prunin ...

  5. 【LeetCode】376. Wiggle Subsequence 解题报告(Python)

    [LeetCode]376. Wiggle Subsequence 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.c ...

  6. 【LeetCode】649. Dota2 Senate 解题报告(Python)

    [LeetCode]649. Dota2 Senate 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地 ...

  7. 【LeetCode】911. Online Election 解题报告(Python)

    [LeetCode]911. Online Election 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ ...

  8. 【LeetCode】886. Possible Bipartition 解题报告(Python)

    [LeetCode]886. Possible Bipartition 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu ...

  9. 【LeetCode】36. Valid Sudoku 解题报告(Python)

    [LeetCode]36. Valid Sudoku 解题报告(Python) 作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 题目地址 ...

随机推荐

  1. EXCEL ctrl+e 百变用法不只是你用的那么简单

    Excel2013版本中,新增加了一个快捷键:Ctrl+E,可以依据字符之间的关系,实现快速填充功能.一些需要使用公式或者其他功能进行解决的问题,现在只要一个快捷键就可以实现了. 用法1:快速拆解出需 ...

  2. 学习java 6.29

    今天是学习Java的第一天. 学习内容:了解了JDK的下载和安装: 学会了如何配置Path环境变量及安装eclipse: 执行了HelloWorld案例: 在Java中关键字需要小写,Java中最基本 ...

  3. 转 Android 多线程:手把手教你使用AsyncTask

    转自:https://www.jianshu.com/p/ee1342fcf5e7 前言 多线程的应用在Android开发中是非常常见的,常用方法主要有: 继承Thread类 实现Runnable接口 ...

  4. EasyExcel读写Excel

    使用过 poi 的开发同学可能都有此体会,每次都要写一坨代码,最后的代码如下面一样: 这样的代码是不是又臭又长?当字段数量多的时候,一不小心还容易写错.阿粉还记得当初使用 poi 导出一个二十多字段的 ...

  5. Linux基础命令---smbpasswd管理samba密码

    smbpasswd smbpasswd指令可以用来修改samba用户的的密码,该指令不仅可以修改本地samba服务器的用户密码,还可以修改远程samba服务器的用户密码. 此命令的适用范围:RedHa ...

  6. 大数据处理系列之(一)Java线程池使用

    前言:最近在做分布式海量数据处理项目,使用到了java的线程池,所以搜集了一些资料对它的使用做了一下总结和探究, 前面介绍的东西大多都是从网上搜集整理而来.文中最核心的东西在于后面两节无界队列线程池和 ...

  7. BigDecimal 计算注意事项

    BigDecimal 在进行除法运算(divide)时一定要注意:如果被除数为变量,一定要指定精度 和 舍入模式,否则会报:Non-terminating decimal expansion; no ...

  8. Centos 7 安装redis,修改配置文件不生效、外网不能访问。

    前提: 在用Centos 7 安装 redis 时,遇上一下几个问题 ,记录下 . 1.修改配置文件,按官网步骤启动,不生效. 2.外网无法访问redis. 步骤: 1.打开centos 虚拟机 ,按 ...

  9. intelliJ破解及JavaEE搭建

    intellij2020.3破解 转载自https://www.exception.site/essay/how-to-free-use-intellij-idea-2019-3 第一步: 下载最新的 ...

  10. Spring Cloud Eureka源码分析之服务注册的流程与数据存储设计!

    Spring Cloud是一个生态,它提供了一套标准,这套标准可以通过不同的组件来实现,其中就包含服务注册/发现.熔断.负载均衡等,在spring-cloud-common这个包中,org.sprin ...