969. 煎饼排序

This commit is contained in:
li-chx 2025-09-07 01:16:07 +08:00
parent bfcbfef2c0
commit 817cef54c7
1 changed files with 17 additions and 33 deletions

View File

@ -1,44 +1,28 @@
mod tree;
use std::rc::Rc;
use std::cell::RefCell;
use std::collections::HashMap;
use tree::{TreeNode, build_tree};
struct Solution;
impl Solution {
fn dfs(root: Option<Rc<RefCell<TreeNode>>>, target: i64) -> (HashMap<i64,i32>,i32) {
if root.is_none() {
return (HashMap::new(),0);
pub fn pancake_sort(arr: Vec<i32>) -> Vec<i32> {
let mut arr = arr;
let mut ans = vec![];
for i in (1..arr.len()+1).rev() {
if arr[i-1] == i as i32 {
continue;
}
let node = root.unwrap();
let val = node.borrow().val;
let val = val as i64;
let mut ans = if val == target { 1 } else { 0 };
let (left,left_ans) = Self::dfs(node.borrow().left.clone(), target);
let (right, right_ans) = Self::dfs(node.borrow().right.clone(), target);
ans += left_ans + right_ans;
ans += *left.get(&(target - val)).unwrap_or(&0);
ans += *right.get(&(target - val)).unwrap_or(&0);
let mut map = HashMap::new();
map.insert(val, 1);
for (k,v) in left.iter().chain(right.iter()) {
*map.entry(k + val).or_insert(0) += v;
let mut index = 0;
while arr[index] != i as i32 {
index += 1;
}
(map,ans)
ans.push((index + 1) as i32);
arr[0..index + 1].reverse();
ans.push(i as i32);
arr[0..i].reverse();
println!("{:?}", arr);
}
pub fn path_sum(root: Option<Rc<RefCell<TreeNode>>>, target_sum: i32) -> i32 {
let (_,ans) = Self::dfs(root, target_sum as i64);
ans
}
}
fn main() {
let vals = vec![
Some(10), Some(5), Some(-3), Some(3), Some(2), None, Some(11),
Some(3), Some(-2), None, Some(1)
];
let root = build_tree(&vals);
let sl = Solution::path_sum(root, 8);
let sl = Solution::pancake_sort(vec![3, 2, 4, 1]);
println!("{:?}", sl);
}