Skip to content

Added 0473-matchsticks-to-square.rs #2280

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions rust/0179-largest-number.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
use std::cmp::Ordering;

impl Solution {
pub fn largest_number(nums: Vec<i32>) -> String {
let mut ans = String::new();
let mut nums = nums;
let mut strs = nums.into_iter().map(|e| e.to_string()).collect::<Vec<String>>();
strs.sort_by(|a, b| {
let a_first = a.clone() + &*b;
let b_first = b.clone() + &*a;
b_first.cmp(&a_first)
});
for num in strs {
if ans == "0" && num == "0" {continue}
ans.push_str(&*num.to_string())
}

ans
}
}
36 changes: 36 additions & 0 deletions rust/0473-matchsticks-to-square.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
impl Solution {
pub fn makesquare(matchsticks: Vec<i32>) -> bool {
fn backtrack(
sides: &mut [i64; 4],
matches: &Vec<i32>,
idx: usize,
length: i64
) -> bool {
if idx >= matches.len() {
return true
}

for i in 0..4 {
if sides[i] + matches[idx] as i64 <= length {
sides[i] += matches[idx] as i64;
if backtrack(sides, matches, idx + 1, length) {
return true
}
sides[i] -= matches[idx] as i64
}
}
false
}

let mut total = 0;
for mat in matchsticks.iter() {
total += *mat as i64;
}
let mut matchsticks = matchsticks;
matchsticks.sort_by_key(|e| std::cmp::Reverse(*w));

let side = total / 4;

backtrack(&mut [0, 0, 0, 0], &matchsticks, 0, side)
}
}