题解 | #剪绳子#
剪绳子
https://www.nowcoder.com/practice/57d85990ba5b440ab888fc72b0751bf8
- 假设分成3段,然后计算. 1,1,1. 2,2,2 3,3,2 ,最终找到3,3,2 这种切法
- 核心思想是,分成m段时,尽量将每段都分得均匀,这样乘积才是最大的。最后筛选出最大值
struct Solution {}
impl Solution {
fn new() -> Self {
Solution {}
}
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param n int整型
* @return int整型
*/
pub fn cutRope(&self, n: i32) -> i32 {
// write code here
let mut res = n - 1;
for m in 2..n as usize {
let mut tmp = Vec::with_capacity(m);
// 初始化tmp的元素为0
for _ in 0..m {
tmp.push(0);
}
let mut i = n;
let mut index = 0usize;
while i > 0 {
if let Some(v) = tmp.get_mut(index) {
*v += 1;
i -= 1;
index += 1;
index %= m;
}
}
// 计算tmp val的乘积
let mut tmp_res = 1;
for i in &tmp {
tmp_res *= i;
}
if tmp_res > res {
res = tmp_res;
println!("{:?}", tmp);
}
}
res
}
}
#rust#
查看9道真题和解析

