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