LeetCode每日一题(473. Matchsticks to Square)

给定一组火柴,每根火柴都有固定长度。目标是不折断火柴,用所有火柴组成一个正方形。题目提供了若干示例,并指出若火柴总长度不能被4整除,则无法形成正方形。通过排序和优化策略,可以判断是否能用火柴构建正方形。
摘要由CSDN通过智能技术生成

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 <= matchsticks.length <= 15
  • 1 <= matchsticks[i] <= 108

我们把火柴分到四个边上, 至于那根火柴分到哪个边我们不必在意, 我们只需要记录四条边的长度即可, 如果分到最后四条边相等则证明可以组成正方形, 如果所有的分配方式都不能组成正方形,则证明这些火柴无法组成正方形。

该算法中还有几处优化细节, 第一是如果火柴的总长度不能被 4 整除, 则证明无法组成正方形。第二是我们可以将火柴的总长度除以 4 得到正方形的边长, 如果在分配火柴时,某个边长已经大于正方形边长,则不需要再继续分配。第三是我们事先对火柴进行倒序排序, 这样根据第二条, 我们可以更快的否掉一些分配方式


use std::collections::HashSet;

impl Solution {
   
    fn dp(
        matchsticks: &Vec<i32>,
        max: i32,
        i: usize,
        l1: i32,
        l2: i32,
        l3: i32,
        l4: i32,
        visited: &mut HashSet<(usize, i32, i32
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值