├── .gitignore ├── LICENSE ├── README.md ├── crawler.py ├── n0002. Add Two Numbers ├── README.md └── main.rs ├── n0004. Median of Two Sorted Arrays ├── README.md └── main.rs ├── n0008. String to Integer (atoi) ├── README.md └── main.rs ├── n0017. Letter Combinations of a Phone Number ├── README.md └── main.rs ├── n0036. Valid Sudoku ├── README.md └── main.rs ├── n0037. Sudoku Solver ├── README.md └── main.rs ├── n0050. Pow(x, n) ├── README.md └── main.rs ├── n0051. N-Queens ├── README.md └── main.rs ├── n0052. N-Queens II ├── README.md └── main.rs ├── n0058. Length of Last Word ├── README.md └── main.rs ├── n0070. Climbing Stairs ├── README.md └── main.rs ├── n0071. Simplify Path ├── README.md └── main.rs ├── n0072. Edit Distance ├── README.md └── main.rs ├── n0077. Combinations ├── README.md └── main.rs ├── n0093. Restore IP Addresses ├── README.md └── main.rs ├── n0094. Binary Tree Inorder Traversal ├── README.md └── main.rs ├── n0111. Minimum Depth of Binary Tree ├── README.md └── main.rs ├── n0112. Path Sum ├── README.md └── main.rs ├── n0113. Path Sum II ├── README.md └── main.rs ├── n0114. Flatten Binary Tree to Linked List ├── README.md └── main.rs ├── n0124. Binary Tree Maximum Path Sum ├── README.md └── main.rs ├── n0129. Sum Root to Leaf Numbers ├── README.md └── main.rs ├── n0135. Candy ├── README.md └── main.rs ├── n0136. Single Number ├── README.md └── main.rs ├── n0144. Binary Tree Preorder Traversal ├── README.md └── main.rs ├── n0145. Binary Tree Postorder Traversal ├── README.md └── main.rs ├── n0165. Compare Version Numbers ├── README.md └── main.rs ├── n0168. Excel Sheet Column Title ├── README.md └── main.rs ├── n0171. Excel Sheet Column Number ├── README.md └── main.rs ├── n0179. Largest Number ├── README.md └── main.rs ├── n0198. House Robber ├── README.md └── main.rs ├── n0200. Number of Islands ├── README.md └── main.rs ├── n0201. Bitwise AND of Numbers Range ├── README.md └── main.rs ├── n0207. Course Schedule ├── README.md └── main.rs ├── n0210. Course Schedule II ├── README.md └── main.rs ├── n0213. House Robber II ├── README.md └── main.rs ├── n0223. Rectangle Area ├── README.md └── main.rs ├── n0224. Basic Calculator ├── README.md └── main.rs ├── n0227. Basic Calculator II ├── README.md └── main.rs ├── n0241. Different Ways to Add Parentheses ├── README.md └── main.rs ├── n0257. Binary Tree Paths ├── README.md └── main.rs ├── n0279. Perfect Squares ├── README.md └── main.rs ├── n0295. Find Median from Data Stream ├── README.md └── main.rs ├── n0300. Longest Increasing Subsequence ├── README.md └── main.rs ├── n0312. Burst Balloons ├── README.md └── main.rs ├── n0315. Count of Smaller Numbers After Self ├── README.md └── main.rs ├── n0322. Coin Change ├── README.md └── main.rs ├── n0327. Count of Range Sum ├── README.md └── main.rs ├── n0334. Increasing Triplet Subsequence ├── README.md └── main.rs ├── n0337. House Robber III ├── README.md └── main.rs ├── n0343. Integer Break ├── README.md └── main.rs ├── n0349. Intersection of Two Arrays ├── README.md └── main.rs ├── n0354. Russian Doll Envelopes ├── README.md └── main.rs ├── n0363. Max Sum of Rectangle No Larger Than K ├── README.md └── main.rs ├── n0375. Guess Number Higher or Lower II ├── README.md └── main.rs ├── n0383. Ransom Note ├── README.md └── main.rs ├── n0392. Is Subsequence ├── README.md └── main.rs ├── n0401. Binary Watch ├── README.md └── main.rs ├── n0405. Convert a Number to Hexadecimal ├── README.md └── main.rs ├── n0424. Longest Repeating Character Replacement ├── README.md └── main.rs ├── n0437. Path Sum III ├── README.md └── main.rs ├── n0443. String Compression ├── README.md └── main.rs ├── n0455. Assign Cookies ├── README.md └── main.rs ├── n0461. Hamming Distance ├── README.md └── main.rs ├── n0463. Island Perimeter ├── README.md └── main.rs ├── n0494. Target Sum ├── README.md └── main.rs ├── n0514. Freedom Trail ├── README.md └── main.rs ├── n0518. Coin Change 2 ├── README.md └── main.rs ├── n0529. Minesweeper ├── README.md └── main.rs ├── n0539. Minimum Time Difference ├── README.md └── main.rs ├── n0563. Binary Tree Tilt ├── README.md └── main.rs ├── n0583. Delete Operation for Two Strings ├── README.md └── main.rs ├── n0606. Construct String from Binary Tree ├── README.md └── main.rs ├── n0630. Course Schedule III ├── README.md └── main.rs ├── n0661. Image Smoother ├── README.md └── main.rs ├── n0671. Second Minimum Node In a Binary Tree ├── README.md └── main.rs ├── n0673. Number of Longest Increasing Subsequence ├── README.md └── main.rs ├── n0674. Longest Continuous Increasing Subsequence ├── README.md └── main.rs ├── n0679. 24 Game ├── README.md └── main.rs ├── n0687. Longest Univalue Path ├── README.md └── main.rs ├── n0691. Stickers to Spell Word ├── README.md └── main.rs ├── n0695. Max Area of Island ├── README.md └── main.rs ├── n0699. Falling Squares ├── README.md └── main.rs ├── n0728. Self Dividing Numbers ├── README.md └── main.rs ├── n0740. Delete and Earn ├── README.md └── main.rs ├── n0744. Find Smallest Letter Greater Than Target ├── README.md └── main.rs ├── n0787. Cheapest Flights Within K Stops ├── README.md └── main.rs ├── n0792. Number of Matching Subsequences ├── README.md └── main.rs ├── n0836. Rectangle Overlap ├── README.md └── main.rs ├── n0851. Loud and Rich ├── README.md └── main.rs ├── n0856. Score of Parentheses ├── README.md └── main.rs ├── n0861. Score After Flipping Matrix ├── README.md └── main.rs ├── n0876. Middle of the Linked List ├── README.md └── main.rs ├── n0877. Stone Game ├── README.md └── main.rs ├── n0902. Numbers At Most N Given Digit Set ├── README.md └── main.rs ├── n0922. Sort Array By Parity II ├── README.md └── main.rs ├── n0935. Knight Dialer ├── README.md └── main.rs ├── n0977. Squares of a Sorted Array ├── README.md └── main.rs ├── n0980. Unique Paths III ├── README.md └── main.rs ├── n0982. Triples with Bitwise AND Equal To Zero ├── README.md └── main.rs ├── n0983. Minimum Cost For Tickets ├── README.md └── main.rs ├── n0991. Broken Calculator ├── README.md └── main.rs ├── n0995. Minimum Number of K Consecutive Bit Flips ├── README.md └── main.rs ├── n1000. Minimum Cost to Merge Stones ├── README.md └── main.rs ├── n1004. Max Consecutive Ones III ├── README.md └── main.rs ├── n1005. Maximize Sum Of Array After K Negations ├── README.md └── main.rs ├── n1006. Clumsy Factorial ├── README.md └── main.rs ├── n1007. Minimum Domino Rotations For Equal Row ├── README.md └── main.rs ├── n1008. Construct Binary Search Tree from Preorder Traversal ├── README.md └── main.rs ├── n1009. Complement of Base 10 Integer ├── README.md └── main.rs ├── n1010. Pairs of Songs With Total Durations Divisible by 60 ├── README.md └── main.rs ├── n1011. Capacity To Ship Packages Within D Days ├── README.md └── main.rs ├── n1013. Partition Array Into Three Parts With Equal Sum ├── README.md └── main.rs ├── n1014. Best Sightseeing Pair ├── README.md └── main.rs ├── n1015. Smallest Integer Divisible by K ├── README.md └── main.rs ├── n1016. Binary String With Substrings Representing 1 To N ├── README.md └── main.rs ├── n1017. Convert to Base -2 ├── README.md └── main.rs ├── n1018. Binary Prefix Divisible By 5 ├── README.md └── main.rs ├── n1019. Next Greater Node In Linked List ├── README.md └── main.rs ├── n1020. Number of Enclaves ├── README.md └── main.rs ├── n1021. Remove Outermost Parentheses ├── README.md └── main.rs ├── n1022. Sum of Root To Leaf Binary Numbers ├── README.md └── main.rs ├── n1023. Camelcase Matching ├── README.md └── main.rs ├── n1024. Video Stitching ├── README.md └── main.rs ├── n1025. Divisor Game ├── README.md └── main.rs ├── n1026. Maximum Difference Between Node and Ancestor ├── README.md └── main.rs ├── n1027. Longest Arithmetic Sequence ├── README.md └── main.rs ├── n1028. Recover a Tree From Preorder Traversal ├── README.md └── main.rs └── n1033. Moving Stones Until Consecutive ├── README.md └── main.rs /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | __pycache__ 3 | /leetcode.sqlite 4 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 Netcan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /n0002. Add Two Numbers/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | // Definition for singly-linked list. 5 | // #[derive(PartialEq, Eq, Clone, Debug)] 6 | // pub struct ListNode { 7 | // pub val: i32, 8 | // pub next: Option> 9 | // } 10 | // 11 | // impl ListNode { 12 | // #[inline] 13 | // fn new(val: i32) -> Self { 14 | // ListNode { 15 | // next: None, 16 | // val 17 | // } 18 | // } 19 | // } 20 | 21 | impl Solution { 22 | pub fn add_two_numbers(l1: Option>, l2: Option>) -> Option> { 23 | let (mut p, mut q) = (&l1, &l2); 24 | let mut head: Option> = None; 25 | let mut cur = &mut head; 26 | 27 | let mut shift = 0; // 进位 28 | while (p.is_some() || q.is_some()) { 29 | let d = if p.is_some() { p.as_ref().unwrap().val } 30 | else { 0 } + 31 | if q.is_some() { q.as_ref().unwrap().val } 32 | else { 0 } + 33 | shift; 34 | 35 | *cur = Some(Box::new(ListNode::new(d % 10))); 36 | cur = &mut cur.as_mut().unwrap().next; 37 | shift = d / 10; 38 | 39 | if p.is_some() { p = &p.as_ref().unwrap().next; } 40 | if q.is_some() { q = &q.as_ref().unwrap().next; } 41 | } 42 | 43 | if shift > 0 { 44 | *cur = Some(Box::new(ListNode::new(shift))); 45 | } 46 | 47 | head 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /n0004. Median of Two Sorted Arrays/README.md: -------------------------------------------------------------------------------- 1 | # Median of Two Sorted Arrays :star::star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/median-of-two-sorted-arrays](https://leetcode-cn.com/problems/median-of-two-sorted-arrays) 3 | - 执行时间: 12 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-17 16:56 6 | 7 | ## 题目内容 8 |

给定两个大小为 m 和 n 的有序数组 nums1 和 nums2

9 | 10 |

请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。

11 | 12 |

你可以假设 nums1 和 nums2 不会同时为空。

13 | 14 |

示例 1:

15 | 16 |
nums1 = [1, 3]
17 | nums2 = [2]
18 | 
19 | 则中位数是 2.0
20 | 
21 | 22 |

示例 2:

23 | 24 |
nums1 = [1, 2]
25 | nums2 = [3, 4]
26 | 
27 | 则中位数是 (2 + 3)/2 = 2.5
28 | 
29 | 30 | 31 | ## 解法 32 | ```rust 33 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 34 | // Zhihu: https://www.zhihu.com/people/netcan 35 | 36 | impl Solution { 37 | pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { 38 | let (m, n) = (nums1.len(), nums2.len()); 39 | let mid_idx = (m + n - 1) / 2; 40 | 41 | let (mut i, mut j) = (0, 0); 42 | let (mut ans, mut cur_num) = (0.0, 0); 43 | while i < m || j < n { 44 | if j == n || (i < m && nums1[i] <= nums2[j]) { cur_num = nums1[i]; } 45 | else { cur_num = nums2[j]; }; 46 | 47 | if i + j >= mid_idx && i + j <= mid_idx + 1 { 48 | if (m + n) % 2 == 1 { 49 | return cur_num as f64; 50 | } else { 51 | ans += cur_num as f64; 52 | if i + j == mid_idx + 1 { return ans / 2.0; } 53 | } 54 | } 55 | 56 | if j == n || (i < m && nums1[i] <= nums2[j]) { i += 1; } 57 | else { j += 1 }; 58 | } 59 | 60 | ans 61 | } 62 | } 63 | 64 | ``` -------------------------------------------------------------------------------- /n0004. Median of Two Sorted Arrays/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn find_median_sorted_arrays(nums1: Vec, nums2: Vec) -> f64 { 6 | let (m, n) = (nums1.len(), nums2.len()); 7 | let mid_idx = (m + n - 1) / 2; 8 | 9 | let (mut i, mut j) = (0, 0); 10 | let (mut ans, mut cur_num) = (0.0, 0); 11 | while i < m || j < n { 12 | if j == n || (i < m && nums1[i] <= nums2[j]) { cur_num = nums1[i]; } 13 | else { cur_num = nums2[j]; }; 14 | 15 | if i + j >= mid_idx && i + j <= mid_idx + 1 { 16 | if (m + n) % 2 == 1 { 17 | return cur_num as f64; 18 | } else { 19 | ans += cur_num as f64; 20 | if i + j == mid_idx + 1 { return ans / 2.0; } 21 | } 22 | } 23 | 24 | if j == n || (i < m && nums1[i] <= nums2[j]) { i += 1; } 25 | else { j += 1 }; 26 | } 27 | 28 | ans 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /n0008. String to Integer (atoi)/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::i32; 5 | impl Solution { 6 | pub fn my_atoi(str: String) -> i32 { 7 | let mut str = str.trim(); 8 | let mut ret: i64 = 0; 9 | let mut sign: bool = false; 10 | 11 | match str.chars().nth(0) { 12 | Some(c) => { 13 | match c { 14 | '-' => { 15 | sign = true; 16 | str = &str[1..]; 17 | } 18 | '+' => { 19 | str = &str[1..]; 20 | } 21 | c if c >= '0' && c <= '9' => {} 22 | _ => { return 0; } 23 | } 24 | } 25 | None => { 26 | return 0; 27 | } 28 | } 29 | 30 | for c in str.chars() { 31 | if c >= '0' && c <= '9' { 32 | ret = ret * 10 + c as i64 - '0' as i64; 33 | } else { break; } 34 | 35 | match sign { 36 | true if -ret < i32::MIN as i64 => {return i32::MIN;} 37 | false if ret > i32::MAX as i64 => {return i32::MAX;} 38 | _ => {} 39 | } 40 | } 41 | if sign { 42 | ret = -ret; 43 | } 44 | 45 | 46 | 47 | ret as i32 48 | } 49 | } 50 | 51 | -------------------------------------------------------------------------------- /n0017. Letter Combinations of a Phone Number/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | 6 | const ALPHA: [&'static str; 10] = [ 7 | "", // 0 8 | "", // 1 9 | "abc", // 2 10 | "def", // 3 11 | "ghi", // 4 12 | "jkl", // 5 13 | "mno", // 6 14 | "pqrs", // 7 15 | "tuv", // 8 16 | "wxyz", // 9 17 | ]; 18 | pub fn letter_combinations(digits: String) -> Vec { 19 | let mut ret = Vec::new(); 20 | if digits.len() == 0 { 21 | return ret; 22 | } 23 | Self::dfs(&digits, &mut String::new(), &mut ret); 24 | ret 25 | } 26 | 27 | fn dfs(digits: &str, comb: &mut String, ret: &mut Vec) { 28 | if digits.len() == 0 { 29 | ret.push(comb.clone()); 30 | return; 31 | } 32 | 33 | if let Some(c) = digits.chars().nth(0) { 34 | for cc in Self::ALPHA[c as usize - '0' as usize].chars() { 35 | comb.push(cc); 36 | Self::dfs(&digits[1..], comb, ret); 37 | comb.pop(); 38 | } 39 | } 40 | } 41 | } 42 | 43 | -------------------------------------------------------------------------------- /n0036. Valid Sudoku/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn is_valid_sudoku(board: Vec>) -> bool { 6 | // 快速检索第i, j列, 第k宫的数字是否被占用 7 | let mut line = [[false; 9]; 9]; // j 8 | let mut column = [[false; 9]; 9]; // i 9 | let mut ceil = [[false; 9]; 9]; // k 10 | // 初始化 11 | for j in 0..9 as usize { 12 | for i in 0..9 as usize { 13 | let num = match board[j][i].to_digit(10) { 14 | Some(n) => (n - 1) as usize, 15 | None => continue 16 | }; 17 | if line[j][num] || column[i][num] || ceil[Solution::ceil_k((j, i))][num] { 18 | return false; 19 | } 20 | line[j][num] = true; 21 | column[i][num] = true; 22 | ceil[Solution::ceil_k((j, i))][num] = true; 23 | } 24 | } 25 | return true; 26 | } 27 | 28 | // 求出pos属于第几个ceil 29 | fn ceil_k(pos: (usize, usize)) -> usize { 30 | return (pos.0 / 3) * 3 + pos.1 / 3; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /n0050. Pow(x, n)/README.md: -------------------------------------------------------------------------------- 1 | # Pow(x, n) :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/powx-n](https://leetcode-cn.com/problems/powx-n) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-10 23:16 6 | 7 | ## 题目内容 8 |

实现 pow(x, n) ,即计算 x 的 n 次幂函数。

9 | 10 |

示例 1:

11 | 12 |
输入: 2.00000, 10
13 | 输出: 1024.00000
14 | 
15 | 16 |

示例 2:

17 | 18 |
输入: 2.10000, 3
19 | 输出: 9.26100
20 | 
21 | 22 |

示例 3:

23 | 24 |
输入: 2.00000, -2
25 | 输出: 0.25000
26 | 解释: 2-2 = 1/22 = 1/4 = 0.25
27 | 28 |

说明:

29 | 30 |
    31 |
  • -100.0 < x < 100.0
  • 32 |
  • n 是 32 位有符号整数,其数值范围是 [−231, 231 − 1] 。
  • 33 |
34 | 35 | 36 | ## 解法 37 | ```rust 38 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 39 | // Zhihu: https://www.zhihu.com/people/netcan 40 | 41 | impl Solution { 42 | pub fn my_pow(x: f64, mut n: i32) -> f64 { 43 | let mut x = if n < 0 { 1.0 / x } else { x }; 44 | let mut ret: f64 = 1.0; 45 | while n != 0 { 46 | if n.abs() % 2 == 1 { 47 | ret *= x; 48 | } 49 | x *= x; 50 | n /= 2; 51 | } 52 | ret 53 | } 54 | } 55 | 56 | #[cfg(test)] 57 | mod tests { 58 | use super::*; 59 | #[test] 60 | fn test_2_10() { 61 | assert_eq!(Solution::my_pow(2.0, 10), 1024.0); 62 | } 63 | #[test] 64 | fn test_2_2() { 65 | assert_eq!(Solution::my_pow(2.0, -2), 0.25); 66 | } 67 | } 68 | 69 | ``` -------------------------------------------------------------------------------- /n0050. Pow(x, n)/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn my_pow(x: f64, mut n: i32) -> f64 { 6 | let mut x = if n < 0 { 1.0 / x } else { x }; 7 | let mut ret: f64 = 1.0; 8 | while n != 0 { 9 | if n.abs() % 2 == 1 { 10 | ret *= x; 11 | } 12 | x *= x; 13 | n /= 2; 14 | } 15 | ret 16 | } 17 | } 18 | 19 | #[cfg(test)] 20 | mod tests { 21 | use super::*; 22 | #[test] 23 | fn test_2_10() { 24 | assert_eq!(Solution::my_pow(2.0, 10), 1024.0); 25 | } 26 | #[test] 27 | fn test_2_2() { 28 | assert_eq!(Solution::my_pow(2.0, -2), 0.25); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /n0051. N-Queens/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | 6 | impl Solution { 7 | pub fn solve_n_queens(n: i32) -> Vec> { 8 | let mut board: Vec> = iter::repeat( 9 | iter::repeat(false).take(n as usize).collect() 10 | ).take(n as usize).collect(); 11 | let mut solv: Vec> = Vec::new(); 12 | Solution::total_n_queens_(0, &mut board, &mut solv); 13 | solv 14 | } 15 | 16 | fn check(pos: (usize, usize), board: &mut Vec>) -> bool { 17 | let n = board.len(); 18 | for j in 0..n { 19 | for i in 0..n { 20 | if j == pos.0 || i == pos.1 || 21 | j + i == pos.1 + pos.0 || i + pos.0 == pos.1 + j { 22 | if board[j][i] { 23 | return false; 24 | } 25 | } 26 | } 27 | } 28 | true 29 | } 30 | 31 | fn total_n_queens_(depth: usize, board: &mut Vec>, solv: &mut Vec>) { 32 | let n = board.len(); 33 | if depth == n { 34 | solv.push( 35 | board.iter().map(|v| { 36 | v.iter().map(|x| { 37 | if *x { "Q".to_string() } else { ".".to_string() } 38 | }).collect::>().join("") 39 | }).collect() 40 | ); 41 | return; 42 | } 43 | for i in 0..n { 44 | // 可放置 45 | if Solution::check((depth, i), board) { 46 | board[depth][i] = true; 47 | Solution::total_n_queens_(depth + 1, board, solv); 48 | board[depth][i] = false; 49 | } 50 | } 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /n0052. N-Queens II/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | 6 | impl Solution { 7 | pub fn total_n_queens(n: i32) -> i32 { 8 | let mut board: Vec> = iter::repeat( 9 | iter::repeat(false).take(n as usize).collect() 10 | ).take(n as usize).collect(); 11 | Solution::total_n_queens_(0, &mut board) 12 | } 13 | 14 | fn check(pos: (usize, usize), board: &mut Vec>) -> bool { 15 | let n = board.len(); 16 | for j in 0..n { 17 | for i in 0..n { 18 | if j == pos.0 || i == pos.1 || 19 | j + i == pos.1 + pos.0 || i + pos.0 == pos.1 + j { 20 | if board[j][i] { 21 | return false; 22 | } 23 | } 24 | } 25 | } 26 | true 27 | } 28 | 29 | fn total_n_queens_(depth: usize, board: &mut Vec>) -> i32 { 30 | let n = board.len(); 31 | if depth == n { 32 | return 1; 33 | } 34 | let mut ret = 0; 35 | for i in 0..n { 36 | // 可放置 37 | if Solution::check((depth, i), board) { 38 | board[depth][i] = true; 39 | ret += Solution::total_n_queens_(depth + 1, board); 40 | board[depth][i] = false; 41 | } 42 | } 43 | ret 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /n0058. Length of Last Word/README.md: -------------------------------------------------------------------------------- 1 | # Length of Last Word :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/length-of-last-word](https://leetcode-cn.com/problems/length-of-last-word) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-05 19:11 6 | 7 | ## 题目内容 8 |

给定一个仅包含大小写字母和空格 ' ' 的字符串,返回其最后一个单词的长度。

9 | 10 |

如果不存在最后一个单词,请返回 0 。

11 | 12 |

说明:一个单词是指由字母组成,但不包含任何空格的字符串。

13 | 14 |

示例:

15 | 16 |
输入: "Hello World"
17 | 输出: 5
18 | 
19 | 20 | 21 | ## 解法 22 | ```rust 23 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 24 | // Zhihu: https://www.zhihu.com/people/netcan 25 | 26 | impl Solution { 27 | pub fn length_of_last_word(s: String) -> i32 { 28 | let words: Vec<&str> = s.split_whitespace().collect(); 29 | if words.len() == 0 { 30 | return 0; 31 | } 32 | return words[words.len() - 1].len() as i32; 33 | 34 | } 35 | } 36 | 37 | 38 | ``` -------------------------------------------------------------------------------- /n0058. Length of Last Word/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn length_of_last_word(s: String) -> i32 { 6 | let words: Vec<&str> = s.split_whitespace().collect(); 7 | if words.len() == 0 { 8 | return 0; 9 | } 10 | return words[words.len() - 1].len() as i32; 11 | 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /n0070. Climbing Stairs/README.md: -------------------------------------------------------------------------------- 1 | # Climbing Stairs :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/climbing-stairs](https://leetcode-cn.com/problems/climbing-stairs) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-05 19:27 6 | 7 | ## 题目内容 8 |

假设你正在爬楼梯。需要 n 阶你才能到达楼顶。

9 | 10 |

每次你可以爬 1 或 2 个台阶。你有多少种不同的方法可以爬到楼顶呢?

11 | 12 |

注意:给定 n 是一个正整数。

13 | 14 |

示例 1:

15 | 16 |
输入: 2
17 | 输出: 2
18 | 解释: 有两种方法可以爬到楼顶。
19 | 1.  1 阶 + 1 阶
20 | 2.  2 阶
21 | 22 |

示例 2:

23 | 24 |
输入: 3
25 | 输出: 3
26 | 解释: 有三种方法可以爬到楼顶。
27 | 1.  1 阶 + 1 阶 + 1 阶
28 | 2.  1 阶 + 2 阶
29 | 3.  2 阶 + 1 阶
30 | 
31 | 32 | 33 | ## 解法 34 | ```rust 35 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 36 | // Zhihu: https://www.zhihu.com/people/netcan 37 | 38 | impl Solution { 39 | pub fn climb_stairs(n: i32) -> i32 { 40 | let mut vec = vec![0; (n + 2) as usize]; 41 | vec[1] = 1; 42 | vec[2] = 2; 43 | for i in (3..=n as usize) { 44 | vec[i] = vec[i - 1] + vec[i - 2]; 45 | } 46 | vec[n as usize] 47 | } 48 | } 49 | 50 | 51 | ``` -------------------------------------------------------------------------------- /n0070. Climbing Stairs/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn climb_stairs(n: i32) -> i32 { 6 | let mut vec = vec![0; (n + 2) as usize]; 7 | vec[1] = 1; 8 | vec[2] = 2; 9 | for i in (3..=n as usize) { 10 | vec[i] = vec[i - 1] + vec[i - 2]; 11 | } 12 | vec[n as usize] 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /n0071. Simplify Path/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn simplify_path(path: String) -> String { 6 | let dir: Vec<&str> = path.split('/').collect(); 7 | let mut dir_abs = Vec::new(); 8 | for d in &dir { 9 | if d.len() == 0 || *d == "." { 10 | continue; 11 | } else if *d == ".." { 12 | dir_abs.pop(); 13 | continue; 14 | } 15 | dir_abs.push(*d); 16 | } 17 | 18 | let ret = "/".to_owned() + &dir_abs.join("/"); 19 | ret 20 | } 21 | } 22 | 23 | #[cfg(test)] 24 | mod tests { 25 | use super::Solution; 26 | #[test] 27 | fn test_1() { 28 | assert_eq!(Solution::simplify_path("/asdf/./sdf/".to_string()), "/asdf/sdf"); 29 | } 30 | 31 | #[test] 32 | fn test_2() { 33 | assert_eq!(Solution::simplify_path("/home/".to_string()), "/home"); 34 | } 35 | 36 | #[test] 37 | fn test_3() { 38 | assert_eq!(Solution::simplify_path("/home//foo/".to_string()), "/home/foo"); 39 | } 40 | 41 | #[test] 42 | fn test_4() { 43 | assert_eq!(Solution::simplify_path("/a/./b/../../c/".to_string()), "/c"); 44 | } 45 | 46 | #[test] 47 | fn test_5() { 48 | assert_eq!(Solution::simplify_path("/a/../../b/../c//.//".to_string()), "/c"); 49 | } 50 | 51 | #[test] 52 | fn test_6() { 53 | assert_eq!(Solution::simplify_path("/a//b////c/d//././/..".to_string()), "/a/b/c"); 54 | } 55 | } 56 | 57 | 58 | -------------------------------------------------------------------------------- /n0072. Edit Distance/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | impl Solution { 6 | // dp[i][j]: word[0..i) -> word[0..j) step 7 | // dp[i][j] = dp[i-1][j-1] if word1[i-1] == word2[j-1] 8 | // else = min( 9 | // dp[i-1][j-1] + 1, change word1[i-1] to word2[j-1] 10 | // dp[i-1][j] + 1, remove word1[i-1] 11 | // dp[i][j-1] + 1, add word2[j-1] 12 | // ) 13 | pub fn min_distance(word1: String, word2: String) -> i32 { 14 | let (m, n) = (word1.len(), word2.len()); 15 | let (word1, word2) = (word1.into_bytes(), word2.into_bytes()); 16 | let mut dp:Vec> = iter::repeat(vec![0; word2.len() + 1]).take(word1.len() + 1).collect(); 17 | for i in 0..=m { dp[i][0] = i as i32; } 18 | for j in 0..=n { dp[0][j] = j as i32; } 19 | 20 | for (i, &c1) in word1.iter().enumerate() { 21 | for (j, &c2) in word2.iter().enumerate() { 22 | dp[i + 1][j + 1] = if c1 == c2 { 23 | dp[i][j] 24 | } else { 25 | dp[i][j].min(dp[i + 1][j]).min(dp[i][j+1]) + 1 26 | } 27 | } 28 | } 29 | 30 | dp[m][n] 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /n0077. Combinations/README.md: -------------------------------------------------------------------------------- 1 | # Combinations :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/combinations](https://leetcode-cn.com/problems/combinations) 3 | - 执行时间: 12 ms 4 | - 内存消耗: 3.2 MB 5 | - 通过日期: 2019-02-18 16:39 6 | 7 | ## 题目内容 8 |

给定两个整数 nk,返回 1 ... n 中所有可能的 k 个数的组合。

9 | 10 |

示例:

11 | 12 |
输入: n = 4, k = 2
13 | 输出:
14 | [
15 |   [2,4],
16 |   [3,4],
17 |   [2,3],
18 |   [1,2],
19 |   [1,3],
20 |   [1,4],
21 | ]
22 | 23 | 24 | ## 解法 25 | ```rust 26 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 27 | // Zhihu: https://www.zhihu.com/people/netcan 28 | 29 | impl Solution { 30 | pub fn combine(n: i32, k: i32) -> Vec> { 31 | let mut ret = vec![]; 32 | let mut temp = Vec::new(); 33 | Self::dfs(1, n, k, &mut temp, &mut ret); 34 | 35 | ret 36 | } 37 | 38 | fn dfs(cur: i32, n: i32, k: i32, array: &mut Vec, ret: &mut Vec>) { 39 | if array.len() == k as usize { 40 | ret.push(array.clone()); 41 | return; 42 | } 43 | for i in cur..n+1 { 44 | array.push(i); 45 | Self::dfs(i + 1, n, k, array, ret); 46 | array.pop(); 47 | } 48 | } 49 | } 50 | 51 | 52 | ``` -------------------------------------------------------------------------------- /n0077. Combinations/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn combine(n: i32, k: i32) -> Vec> { 6 | let mut ret = vec![]; 7 | let mut temp = Vec::new(); 8 | Self::dfs(1, n, k, &mut temp, &mut ret); 9 | 10 | ret 11 | } 12 | 13 | fn dfs(cur: i32, n: i32, k: i32, array: &mut Vec, ret: &mut Vec>) { 14 | if array.len() == k as usize { 15 | ret.push(array.clone()); 16 | return; 17 | } 18 | for i in cur..n+1 { 19 | array.push(i); 20 | Self::dfs(i + 1, n, k, array, ret); 21 | array.pop(); 22 | } 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /n0093. Restore IP Addresses/README.md: -------------------------------------------------------------------------------- 1 | # Restore IP Addresses :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/restore-ip-addresses](https://leetcode-cn.com/problems/restore-ip-addresses) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-04-18 21:37 6 | 7 | ## 题目内容 8 |

给定一个只包含数字的字符串,复原它并返回所有可能的 IP 地址格式。

9 | 10 |

示例:

11 | 12 |
输入: "25525511135"
13 | 输出: ["255.255.11.135", "255.255.111.35"]
14 | 15 | 16 | ## 解法 17 | ```rust 18 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 19 | // Zhihu: https://www.zhihu.com/people/netcan 20 | 21 | impl Solution { 22 | pub fn restore_ip_addresses(s: String) -> Vec { 23 | let s: Vec = s.into_bytes().into_iter().map(|x| (x - '0' as u8) as i32).collect(); 24 | let mut ip_addrs: Vec = vec![]; 25 | 26 | Solution::restore_ip_addresses_(&s, s.len(), &mut Vec::new(), &mut ip_addrs); 27 | ip_addrs 28 | } 29 | pub fn restore_ip_addresses_(s: &[i32], s_len: usize, ip: &mut Vec, ip_addrs: &mut Vec) { 30 | if ip.len() > 4 { return; } 31 | else if ip.len() == 4 && s.len() == 0 { 32 | let ip_addr = ip.iter().map(|x| x.to_string()).collect::>().join("."); 33 | if ip_addr.len() - 3 == s_len { ip_addrs.push(ip_addr); } 34 | } 35 | let mut num = 0; 36 | for i in 0..s.len() { 37 | num = num * 10 + s[i]; 38 | if num < 256 { 39 | ip.push(num); 40 | Solution::restore_ip_addresses_(&s[i + 1..], s_len, ip, ip_addrs); 41 | ip.pop(); 42 | } else { break; } 43 | } 44 | 45 | } 46 | } 47 | 48 | 49 | ``` -------------------------------------------------------------------------------- /n0093. Restore IP Addresses/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn restore_ip_addresses(s: String) -> Vec { 6 | let s: Vec = s.into_bytes().into_iter().map(|x| (x - '0' as u8) as i32).collect(); 7 | let mut ip_addrs: Vec = vec![]; 8 | 9 | Solution::restore_ip_addresses_(&s, s.len(), &mut Vec::new(), &mut ip_addrs); 10 | ip_addrs 11 | } 12 | pub fn restore_ip_addresses_(s: &[i32], s_len: usize, ip: &mut Vec, ip_addrs: &mut Vec) { 13 | if ip.len() > 4 { return; } 14 | else if ip.len() == 4 && s.len() == 0 { 15 | let ip_addr = ip.iter().map(|x| x.to_string()).collect::>().join("."); 16 | if ip_addr.len() - 3 == s_len { ip_addrs.push(ip_addr); } 17 | } 18 | let mut num = 0; 19 | for i in 0..s.len() { 20 | num = num * 10 + s[i]; 21 | if num < 256 { 22 | ip.push(num); 23 | Solution::restore_ip_addresses_(&s[i + 1..], s_len, ip, ip_addrs); 24 | ip.pop(); 25 | } else { break; } 26 | } 27 | 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /n0094. Binary Tree Inorder Traversal/README.md: -------------------------------------------------------------------------------- 1 | # Binary Tree Inorder Traversal :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/binary-tree-inorder-traversal](https://leetcode-cn.com/problems/binary-tree-inorder-traversal) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 725 KB 5 | - 通过日期: 2019-02-19 20:44 6 | 7 | ## 题目内容 8 |

给定一个二叉树,返回它的中序 遍历。

9 | 10 |

示例:

11 | 12 |
输入: [1,null,2,3]
13 |    1
14 |     \
15 |      2
16 |     /
17 |    3
18 | 
19 | 输出: [1,3,2]
20 | 21 |

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

22 | 23 | 24 | ## 解法 25 | ```rust 26 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 27 | // Zhihu: https://www.zhihu.com/people/netcan 28 | 29 | use std::rc::Rc; 30 | use std::cell::RefCell; 31 | impl Solution { 32 | pub fn inorder_traversal(root: Option>>) -> Vec { 33 | let mut ret = Vec::new(); 34 | match root { 35 | None => {}, 36 | Some(root) => { 37 | ret.append(&mut Self::inorder_traversal(root.borrow().left.clone())); 38 | ret.push(root.borrow().val); 39 | ret.append(&mut Self::inorder_traversal(root.borrow().right.clone())); 40 | } 41 | } 42 | 43 | ret 44 | } 45 | } 46 | 47 | 48 | ``` -------------------------------------------------------------------------------- /n0094. Binary Tree Inorder Traversal/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn inorder_traversal(root: Option>>) -> Vec { 8 | let mut ret = Vec::new(); 9 | match root { 10 | None => {}, 11 | Some(root) => { 12 | ret.append(&mut Self::inorder_traversal(root.borrow().left.clone())); 13 | ret.push(root.borrow().val); 14 | ret.append(&mut Self::inorder_traversal(root.borrow().right.clone())); 15 | } 16 | } 17 | 18 | ret 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /n0111. Minimum Depth of Binary Tree/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | use std::collections::VecDeque; 7 | impl Solution { 8 | fn min_depth(root: Option>>) -> i32 { 9 | if let None = root { 10 | return 0; 11 | } 12 | let mut que: VecDeque<(Option>>, i32)> = VecDeque::new(); 13 | que.push_back((root, 1)); 14 | while !que.is_empty() { 15 | let (node, depth) = que.pop_front().unwrap(); 16 | match node { 17 | Some(node) => { 18 | let node = node.borrow(); 19 | if let None = node.left { 20 | if let None = node.right { 21 | return depth; 22 | } 23 | } 24 | 25 | if let Some(_) = node.left { 26 | que.push_back((node.left.clone(), depth + 1)); 27 | } 28 | 29 | if let Some(_) = node.right { 30 | que.push_back((node.right.clone(), depth + 1)); 31 | } 32 | 33 | }, 34 | None => { 35 | return depth; 36 | } 37 | } 38 | 39 | } 40 | 0 41 | 42 | } 43 | } 44 | 45 | -------------------------------------------------------------------------------- /n0112. Path Sum/README.md: -------------------------------------------------------------------------------- 1 | # Path Sum :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/path-sum](https://leetcode-cn.com/problems/path-sum) 3 | - 执行时间: 4 ms 4 | - 内存消耗: 3.1 MB 5 | - 通过日期: 2019-03-10 00:06 6 | 7 | ## 题目内容 8 |

给定一个二叉树和一个目标和,判断该树中是否存在根节点到叶子节点的路径,这条路径上所有节点值相加等于目标和。

9 | 10 |

说明: 叶子节点是指没有子节点的节点。

11 | 12 |

示例: 
13 | 给定如下二叉树,以及目标和 sum = 22

14 | 15 |
              5
16 |              / \
17 |             4   8
18 |            /   / \
19 |           11  13  4
20 |          /  \      \
21 |         7    2      1
22 | 
23 | 24 |

返回 true, 因为存在目标和为 22 的根节点到叶子节点的路径 5->4->11->2

25 | 26 | 27 | ## 解法 28 | ```rust 29 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 30 | // Zhihu: https://www.zhihu.com/people/netcan 31 | 32 | use std::rc::Rc; 33 | use std::cell::RefCell; 34 | 35 | impl Solution { 36 | pub fn has_path_sum(root: Option>>, sum: i32) -> bool { 37 | Solution::has_path_sum_(&root, sum) 38 | } 39 | 40 | fn has_path_sum_(root: &Option>>, sum: i32) -> bool { 41 | match root { 42 | Some(node) => { 43 | let node = node.borrow(); 44 | let diff = sum - node.val; 45 | if node.left.is_none() && 46 | node.right.is_none() && 47 | diff == 0 { return true; } 48 | Solution::has_path_sum_(&node.left, diff) || 49 | Solution::has_path_sum_(&node.right, diff) 50 | }, 51 | None => false 52 | } 53 | } 54 | 55 | } 56 | 57 | ``` -------------------------------------------------------------------------------- /n0112. Path Sum/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | 7 | impl Solution { 8 | pub fn has_path_sum(root: Option>>, sum: i32) -> bool { 9 | Solution::has_path_sum_(&root, sum) 10 | } 11 | 12 | fn has_path_sum_(root: &Option>>, sum: i32) -> bool { 13 | match root { 14 | Some(node) => { 15 | let node = node.borrow(); 16 | let diff = sum - node.val; 17 | if node.left.is_none() && 18 | node.right.is_none() && 19 | diff == 0 { return true; } 20 | Solution::has_path_sum_(&node.left, diff) || 21 | Solution::has_path_sum_(&node.right, diff) 22 | }, 23 | None => false 24 | } 25 | } 26 | 27 | } 28 | -------------------------------------------------------------------------------- /n0113. Path Sum II/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | 7 | impl Solution { 8 | pub fn path_sum(root: Option>>, sum: i32) -> Vec> { 9 | let mut result: Vec> = Vec::new(); 10 | Solution::path_sum_(&root, sum, vec![], &mut result); 11 | result 12 | } 13 | 14 | fn path_sum_(root: &Option>>, sum: i32, mut path: Vec, result: &mut Vec>) { 15 | match root { 16 | Some(node) => { 17 | let node = node.borrow(); 18 | let diff = sum - node.val; 19 | path.push(node.val); 20 | if node.left.is_none() && 21 | node.right.is_none() && 22 | diff == 0 { 23 | result.push(path.clone()); 24 | } 25 | Solution::path_sum_(&node.left, diff, path.clone(), result); 26 | Solution::path_sum_(&node.right, diff, path.clone(), result); 27 | }, 28 | None => {} 29 | } 30 | } 31 | 32 | } 33 | 34 | -------------------------------------------------------------------------------- /n0114. Flatten Binary Tree to Linked List/README.md: -------------------------------------------------------------------------------- 1 | # Flatten Binary Tree to Linked List :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list](https://leetcode-cn.com/problems/flatten-binary-tree-to-linked-list) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-04-09 18:48 6 | 7 | ## 题目内容 8 |

给定一个二叉树,原地将它展开为链表。

9 | 10 |

例如,给定二叉树

11 | 12 |
    1
13 |    / \
14 |   2   5
15 |  / \   \
16 | 3   4   6
17 | 18 |

将其展开为:

19 | 20 |
1
21 |  \
22 |   2
23 |    \
24 |     3
25 |      \
26 |       4
27 |        \
28 |         5
29 |          \
30 |           6
31 | 32 | 33 | ## 解法 34 | ```rust 35 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 36 | // Zhihu: https://www.zhihu.com/people/netcan 37 | 38 | use std::rc::Rc; 39 | use std::cell::RefCell; 40 | impl Solution { 41 | pub fn flatten(root: &mut Option>>) { 42 | // 把左树插到右树上 43 | match &root { 44 | Some(node) => { 45 | let mut node = node.borrow_mut(); 46 | Solution::flatten(&mut node.left); 47 | Solution::flatten(&mut node.right); 48 | // 叶子节点 or 无左子树 49 | if node.left.is_none() { return; } 50 | 51 | let mut right = node.right.take(); 52 | node.right = node.left.take(); // 左子树放到右子树上 53 | 54 | // 遍历到右子树末尾,把剩余右子树接上 55 | let mut p = Rc::clone(node.right.as_ref().unwrap()); 56 | while p.borrow().right.is_some() { 57 | let next_p = Rc::clone(p.borrow().right.as_ref().unwrap()); 58 | p = next_p; 59 | } 60 | p.borrow_mut().right = right.take(); 61 | }, 62 | None => {} 63 | } 64 | } 65 | } 66 | 67 | 68 | ``` -------------------------------------------------------------------------------- /n0114. Flatten Binary Tree to Linked List/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn flatten(root: &mut Option>>) { 8 | // 把左树插到右树上 9 | match &root { 10 | Some(node) => { 11 | let mut node = node.borrow_mut(); 12 | Solution::flatten(&mut node.left); 13 | Solution::flatten(&mut node.right); 14 | // 叶子节点 or 无左子树 15 | if node.left.is_none() { return; } 16 | 17 | let mut right = node.right.take(); 18 | node.right = node.left.take(); // 左子树放到右子树上 19 | 20 | // 遍历到右子树末尾,把剩余右子树接上 21 | let mut p = Rc::clone(node.right.as_ref().unwrap()); 22 | while p.borrow().right.is_some() { 23 | let next_p = Rc::clone(p.borrow().right.as_ref().unwrap()); 24 | p = next_p; 25 | } 26 | p.borrow_mut().right = right.take(); 27 | }, 28 | None => {} 29 | } 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /n0124. Binary Tree Maximum Path Sum/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | use std::cmp::max; 7 | impl Solution { 8 | pub fn max_path_sum(root: Option>>) -> i32 { 9 | let mut max_sum = i32::min_value(); 10 | Solution::max_path_sum_(&root, &mut max_sum); 11 | max_sum 12 | } 13 | 14 | fn max_path_sum_(root: &Option>>, max_sum: &mut i32) -> i32 { 15 | match root { 16 | Some(node) => { 17 | let node = node.borrow(); 18 | let mut lsum = Solution::max_path_sum_(&node.left, max_sum); 19 | if lsum == i32::min_value() { 20 | lsum = 0; 21 | } 22 | let mut rsum = Solution::max_path_sum_(&node.right, max_sum); 23 | if rsum == i32::min_value() { 24 | rsum = 0; 25 | } 26 | lsum += node.val; 27 | rsum += node.val; 28 | 29 | let lrv_max_sum = max(node.val, max(lsum, rsum)); 30 | // println!("lsum: {} rsum: {} lrv:{} val: {}", lsum, rsum, lrv_max_sum, node.val); 31 | *max_sum = max(*max_sum, max(max(lrv_max_sum, lsum + rsum - node.val), node.val)); 32 | 33 | lrv_max_sum 34 | }, 35 | None => { 36 | i32::min_value() 37 | } 38 | } 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /n0129. Sum Root to Leaf Numbers/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | 7 | impl Solution { 8 | pub fn sum_numbers(root: Option>>) -> i32 { 9 | let mut ret = 0; 10 | Solution::sum_numbers_(&root, 0, &mut ret); 11 | ret 12 | } 13 | fn sum_numbers_(root: &Option>>, num: i32, sum: &mut i32) { 14 | match root { 15 | Some(node) => { 16 | let node = node.borrow(); 17 | let num = num * 10 + node.val; 18 | if node.left.is_none() && node.right.is_none() { 19 | *sum += num; 20 | } 21 | Solution::sum_numbers_(&node.left, num, sum); 22 | Solution::sum_numbers_(&node.right, num, sum); 23 | }, 24 | None => {} 25 | } 26 | 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /n0136. Single Number/README.md: -------------------------------------------------------------------------------- 1 | # Single Number :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/single-number](https://leetcode-cn.com/problems/single-number) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.7 MB 5 | - 通过日期: 2019-03-10 01:06 6 | 7 | ## 题目内容 8 |

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

9 | 10 |

说明:

11 | 12 |

你的算法应该具有线性时间复杂度。 你可以不使用额外空间来实现吗?

13 | 14 |

示例 1:

15 | 16 |
输入: [2,2,1]
17 | 输出: 1
18 | 
19 | 20 |

示例 2:

21 | 22 |
输入: [4,1,2,1,2]
23 | 输出: 4
24 | 25 | 26 | ## 解法 27 | ```rust 28 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 29 | // Zhihu: https://www.zhihu.com/people/netcan 30 | 31 | impl Solution { 32 | pub fn single_number(nums: Vec) -> i32 { 33 | nums.iter().fold(0, |a, b| { a ^ b }) 34 | } 35 | } 36 | 37 | ``` -------------------------------------------------------------------------------- /n0136. Single Number/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn single_number(nums: Vec) -> i32 { 6 | nums.iter().fold(0, |a, b| { a ^ b }) 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /n0144. Binary Tree Preorder Traversal/README.md: -------------------------------------------------------------------------------- 1 | # Binary Tree Preorder Traversal :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/binary-tree-preorder-traversal](https://leetcode-cn.com/problems/binary-tree-preorder-traversal) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 712.7 KB 5 | - 通过日期: 2019-02-19 20:46 6 | 7 | ## 题目内容 8 |

给定一个二叉树,返回它的 前序 遍历。

9 | 10 |

 示例:

11 | 12 |
输入: [1,null,2,3]  
13 |    1
14 |     \
15 |      2
16 |     /
17 |    3 
18 | 
19 | 输出: [1,2,3]
20 | 
21 | 22 |

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

23 | 24 | 25 | ## 解法 26 | ```rust 27 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 28 | // Zhihu: https://www.zhihu.com/people/netcan 29 | 30 | use std::rc::Rc; 31 | use std::cell::RefCell; 32 | impl Solution { 33 | pub fn preorder_traversal(root: Option>>) -> Vec { 34 | let mut ret = Vec::new(); 35 | match root { 36 | None => {}, 37 | Some(root) => { 38 | ret.push(root.borrow().val); 39 | ret.append(&mut Self::preorder_traversal(root.borrow().left.clone())); 40 | ret.append(&mut Self::preorder_traversal(root.borrow().right.clone())); 41 | } 42 | } 43 | ret 44 | } 45 | } 46 | 47 | 48 | ``` -------------------------------------------------------------------------------- /n0144. Binary Tree Preorder Traversal/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn preorder_traversal(root: Option>>) -> Vec { 8 | let mut ret = Vec::new(); 9 | match root { 10 | None => {}, 11 | Some(root) => { 12 | ret.push(root.borrow().val); 13 | ret.append(&mut Self::preorder_traversal(root.borrow().left.clone())); 14 | ret.append(&mut Self::preorder_traversal(root.borrow().right.clone())); 15 | } 16 | } 17 | ret 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /n0145. Binary Tree Postorder Traversal/README.md: -------------------------------------------------------------------------------- 1 | # Binary Tree Postorder Traversal :star::star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/binary-tree-postorder-traversal](https://leetcode-cn.com/problems/binary-tree-postorder-traversal) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 708.6 KB 5 | - 通过日期: 2019-02-19 20:47 6 | 7 | ## 题目内容 8 |

给定一个二叉树,返回它的 后序 遍历。

9 | 10 |

示例:

11 | 12 |
输入: [1,null,2,3]  
13 |    1
14 |     \
15 |      2
16 |     /
17 |    3 
18 | 
19 | 输出: [3,2,1]
20 | 21 |

进阶: 递归算法很简单,你可以通过迭代算法完成吗?

22 | 23 | 24 | ## 解法 25 | ```rust 26 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 27 | // Zhihu: https://www.zhihu.com/people/netcan 28 | 29 | use std::rc::Rc; 30 | use std::cell::RefCell; 31 | impl Solution { 32 | pub fn postorder_traversal(root: Option>>) -> Vec { 33 | let mut ret = Vec::new(); 34 | match root { 35 | None => {}, 36 | Some(root) => { 37 | ret.append(&mut Self::postorder_traversal(root.borrow().left.clone())); 38 | ret.append(&mut Self::postorder_traversal(root.borrow().right.clone())); 39 | ret.push(root.borrow().val); 40 | } 41 | } 42 | ret 43 | } 44 | } 45 | 46 | 47 | ``` -------------------------------------------------------------------------------- /n0145. Binary Tree Postorder Traversal/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn postorder_traversal(root: Option>>) -> Vec { 8 | let mut ret = Vec::new(); 9 | match root { 10 | None => {}, 11 | Some(root) => { 12 | ret.append(&mut Self::postorder_traversal(root.borrow().left.clone())); 13 | ret.append(&mut Self::postorder_traversal(root.borrow().right.clone())); 14 | ret.push(root.borrow().val); 15 | } 16 | } 17 | ret 18 | } 19 | } 20 | 21 | -------------------------------------------------------------------------------- /n0165. Compare Version Numbers/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn compare_version(version1: String, version2: String) -> i32 { 6 | if version1.len() <= 0 || version2.len() <= 0 { return 0; } 7 | 8 | let version1: Vec<&str> = version1.split('.').collect(); 9 | let version2: Vec<&str> = version2.split('.').collect(); 10 | let mut i = 0; 11 | while i < version1.len() || i < version2.len() { 12 | let num1: u32 = if i < version1.len() { 13 | version1[i].parse().unwrap() 14 | } else { 0 }; 15 | 16 | let num2: u32 = if i < version2.len() { 17 | version2[i].parse().unwrap() 18 | } else { 0 }; 19 | if num1 > num2 { return 1; } 20 | else if num1 < num2 { return -1; } 21 | i += 1; 22 | } 23 | 24 | 0 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /n0168. Excel Sheet Column Title/README.md: -------------------------------------------------------------------------------- 1 | # Excel Sheet Column Title :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/excel-sheet-column-title](https://leetcode-cn.com/problems/excel-sheet-column-title) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.3 MB 5 | - 通过日期: 2019-04-10 19:58 6 | 7 | ## 题目内容 8 |

给定一个正整数,返回它在 Excel 表中相对应的列名称。

9 | 10 |

例如,

11 | 12 |
    1 -> A
13 |     2 -> B
14 |     3 -> C
15 |     ...
16 |     26 -> Z
17 |     27 -> AA
18 |     28 -> AB 
19 |     ...
20 | 
21 | 22 |

示例 1:

23 | 24 |
输入: 1
25 | 输出: "A"
26 | 
27 | 28 |

示例 2:

29 | 30 |
输入: 28
31 | 输出: "AB"
32 | 
33 | 34 |

示例 3:

35 | 36 |
输入: 701
37 | 输出: "ZY"
38 | 
39 | 40 | 41 | ## 解法 42 | ```rust 43 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 44 | // Zhihu: https://www.zhihu.com/people/netcan 45 | 46 | impl Solution { 47 | pub fn convert_to_title(mut n: i32) -> String { 48 | let mut title = String::new(); 49 | while n != 0 { 50 | title = ((((n - 1) % 26) as u8 + 'A' as u8) as char).to_string() + &title; 51 | n = (n - 1) / 26; 52 | } 53 | title 54 | } 55 | } 56 | 57 | 58 | ``` -------------------------------------------------------------------------------- /n0168. Excel Sheet Column Title/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn convert_to_title(mut n: i32) -> String { 6 | let mut title = String::new(); 7 | while n != 0 { 8 | title = ((((n - 1) % 26) as u8 + 'A' as u8) as char).to_string() + &title; 9 | n = (n - 1) / 26; 10 | } 11 | title 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /n0171. Excel Sheet Column Number/README.md: -------------------------------------------------------------------------------- 1 | # Excel Sheet Column Number :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/excel-sheet-column-number](https://leetcode-cn.com/problems/excel-sheet-column-number) 3 | - 执行时间: 4 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-04-10 19:15 6 | 7 | ## 题目内容 8 |

给定一个Excel表格中的列名称,返回其相应的列序号。

9 | 10 |

例如,

11 | 12 |
    A -> 1
13 |     B -> 2
14 |     C -> 3
15 |     ...
16 |     Z -> 26
17 |     AA -> 27
18 |     AB -> 28 
19 |     ...
20 | 
21 | 22 |

示例 1:

23 | 24 |
输入: "A"
25 | 输出: 1
26 | 
27 | 28 |

示例 2:

29 | 30 |
输入: "AB"
31 | 输出: 28
32 | 
33 | 34 |

示例 3:

35 | 36 |
输入: "ZY"
37 | 输出: 701
38 | 39 |

致谢:
40 | 特别感谢 @ts 添加此问题并创建所有测试用例。

41 | 42 | 43 | ## 解法 44 | ```rust 45 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 46 | // Zhihu: https://www.zhihu.com/people/netcan 47 | 48 | impl Solution { 49 | pub fn title_to_number(s: String) -> i32 { 50 | s.into_bytes() 51 | .into_iter() 52 | .fold(0, |acc, d| { acc * 26 + (d - 'A' as u8 + 1) as i32 }) 53 | } 54 | } 55 | 56 | 57 | ``` -------------------------------------------------------------------------------- /n0171. Excel Sheet Column Number/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn title_to_number(s: String) -> i32 { 6 | s.into_bytes() 7 | .into_iter() 8 | .fold(0, |acc, d| { acc * 26 + (d - 'A' as u8 + 1) as i32 }) 9 | } 10 | } 11 | 12 | -------------------------------------------------------------------------------- /n0198. House Robber/README.md: -------------------------------------------------------------------------------- 1 | # House Robber :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/house-robber](https://leetcode-cn.com/problems/house-robber) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-23 11:50 6 | 7 | ## 题目内容 8 |

你是一个专业的小偷,计划偷窃沿街的房屋。每间房内都藏有一定的现金,影响你偷窃的唯一制约因素就是相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警

9 | 10 |

给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。

11 | 12 |

示例 1:

13 | 14 |
输入: [1,2,3,1]
15 | 输出: 4
16 | 解释: 偷窃 1 号房屋 (金额 = 1) ,然后偷窃 3 号房屋 (金额 = 3)。
17 |      偷窃到的最高金额 = 1 + 3 = 4 。
18 | 19 |

示例 2:

20 | 21 |
输入: [2,7,9,3,1]
22 | 输出: 12
23 | 解释: 偷窃 1 号房屋 (金额 = 2), 偷窃 3 号房屋 (金额 = 9),接着偷窃 5 号房屋 (金额 = 1)。
24 |      偷窃到的最高金额 = 2 + 9 + 1 = 12 。
25 | 
26 | 27 | 28 | ## 解法 29 | ```rust 30 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 31 | // Zhihu: https://www.zhihu.com/people/netcan 32 | 33 | impl Solution { 34 | pub fn rob(nums: Vec) -> i32 { 35 | let mut dp = vec![0; nums.len() + 1]; // 偷第i家时最大收益 36 | for i in 0..nums.len() { 37 | dp[i + 1] = 38 | if i > 0 { dp[0..=i-1].iter().max().unwrap() + nums[i] } 39 | else { nums[i] } 40 | } 41 | *dp.iter().max().unwrap() 42 | } 43 | } 44 | 45 | 46 | ``` -------------------------------------------------------------------------------- /n0198. House Robber/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn rob(nums: Vec) -> i32 { 6 | let mut dp = vec![0; nums.len() + 1]; // 偷第i家时最大收益 7 | for i in 0..nums.len() { 8 | dp[i + 1] = 9 | if i > 0 { dp[0..=i-1].iter().max().unwrap() + nums[i] } 10 | else { nums[i] } 11 | } 12 | *dp.iter().max().unwrap() 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /n0200. Number of Islands/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::VecDeque; 5 | impl Solution { 6 | const dxy: [(i32, i32); 4] = [(0 ,1), (0, -1), (-1, 0), (1, 0)]; 7 | pub fn num_islands(mut grid: Vec>) -> i32 { 8 | let mut cnt: i32 = 0; 9 | for j in (0..grid.len()) { 10 | for i in (0..grid[0].len()) { 11 | if grid[j][i] == '1' { 12 | Solution::find_island(&mut grid, (j as i32, i as i32)); 13 | cnt += 1; 14 | } 15 | } 16 | } 17 | cnt 18 | } 19 | fn find_island(grid: &mut Vec>, pos: (i32, i32)) -> bool { 20 | if grid[pos.0 as usize][pos.1 as usize] == '0' { 21 | false 22 | } else { 23 | let mut que = VecDeque::new(); 24 | let (m, n) = (grid.len(), grid[0].len()); 25 | grid[pos.0 as usize][pos.1 as usize] = '0'; 26 | que.push_back(pos); 27 | while !que.is_empty() { 28 | let last_pos = que.pop_front().unwrap(); 29 | for &d in &Solution::dxy { 30 | let next_pos:(i32, i32) = (last_pos.0 + d.0, last_pos.1 + d.1); 31 | if next_pos.0 >= 0 && next_pos.0 < m as i32 && 32 | next_pos.1 >= 0 && next_pos.1 < n as i32 && 33 | grid[next_pos.0 as usize][next_pos.1 as usize] == '1' { 34 | grid[next_pos.0 as usize][next_pos.1 as usize] = '0'; 35 | que.push_back(next_pos); 36 | } 37 | } 38 | } 39 | 40 | true 41 | } 42 | } 43 | 44 | } 45 | 46 | -------------------------------------------------------------------------------- /n0201. Bitwise AND of Numbers Range/README.md: -------------------------------------------------------------------------------- 1 | # Bitwise AND of Numbers Range :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/bitwise-and-of-numbers-range](https://leetcode-cn.com/problems/bitwise-and-of-numbers-range) 3 | - 执行时间: 24 ms 4 | - 内存消耗: 2.3 MB 5 | - 通过日期: 2019-03-07 12:05 6 | 7 | ## 题目内容 8 |

给定范围 [m, n],其中 0 <= m <= n <= 2147483647,返回此范围内所有数字的按位与(包含 m, n 两端点)。

9 | 10 |

示例 1: 

11 | 12 |
输入: [5,7]
13 | 输出: 4
14 | 15 |

示例 2:

16 | 17 |
输入: [0,1]
18 | 输出: 0
19 | 20 | 21 | ## 解法 22 | ```rust 23 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 24 | // Zhihu: https://www.zhihu.com/people/netcan 25 | 26 | impl Solution { 27 | pub fn range_bitwise_and(m: i32, n: i32) -> i32 { 28 | let m: u32 = m as u32; 29 | let n: u32 = n as u32; 30 | let diff = n - m + 1; 31 | let mut bit_and = 1; 32 | while bit_and < diff { 33 | bit_and <<= 1; 34 | } 35 | (m & !(bit_and - 1) & n) as i32 36 | } 37 | } 38 | 39 | 40 | ``` -------------------------------------------------------------------------------- /n0201. Bitwise AND of Numbers Range/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn range_bitwise_and(m: i32, n: i32) -> i32 { 6 | let m: u32 = m as u32; 7 | let n: u32 = n as u32; 8 | let diff = n - m + 1; 9 | let mut bit_and = 1; 10 | while bit_and < diff { 11 | bit_and <<= 1; 12 | } 13 | (m & !(bit_and - 1) & n) as i32 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /n0207. Course Schedule/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | impl Solution { 6 | pub fn can_finish(num_courses: i32, prerequisites: Vec>) -> bool { 7 | let mut graph = iter::repeat(Vec::::new()).take(num_courses as usize).collect::>>(); 8 | let mut indegree = vec![0; num_courses as usize]; 9 | 10 | // 建图 11 | for edge in &prerequisites { 12 | let (u, v) = (edge[0], edge[1]); 13 | graph[v as usize].push(u); // v->u 14 | indegree[u as usize] += 1; 15 | } 16 | 17 | // 入度为0的节点 18 | let mut S = Vec::new(); 19 | for (node, °ree) in indegree.iter().enumerate() { 20 | if degree == 0 { 21 | S.push(node as i32); 22 | } 23 | } 24 | 25 | while !S.is_empty() { 26 | let v = S.pop().unwrap(); 27 | for &u in &graph[v as usize] { 28 | indegree[u as usize] -= 1; 29 | if indegree[u as usize] == 0 { 30 | S.push(u); 31 | } 32 | } 33 | } 34 | 35 | // 图是否为空 36 | if (indegree.iter().all(|&e| e == 0)) { 37 | true 38 | } else { 39 | false 40 | } 41 | } 42 | } 43 | 44 | -------------------------------------------------------------------------------- /n0210. Course Schedule II/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | impl Solution { 6 | pub fn find_order(num_courses: i32, prerequisites: Vec>) -> Vec { 7 | let mut graph = iter::repeat(Vec::::new()).take(num_courses as usize).collect::>>(); 8 | let mut indegree = vec![0; num_courses as usize]; 9 | 10 | // 建图 11 | for edge in &prerequisites { 12 | let (u, v) = (edge[0], edge[1]); 13 | graph[v as usize].push(u); // v->u 14 | indegree[u as usize] += 1; 15 | } 16 | 17 | // 入度为0的节点 18 | let mut S = Vec::new(); 19 | for (node, °ree) in indegree.iter().enumerate() { 20 | if degree == 0 { 21 | S.push(node as i32); 22 | } 23 | } 24 | 25 | let mut order: Vec = Vec::new(); 26 | while !S.is_empty() { 27 | let v = S.pop().unwrap(); 28 | order.push(v); 29 | for &u in &graph[v as usize] { 30 | indegree[u as usize] -= 1; 31 | if indegree[u as usize] == 0 { 32 | S.push(u); 33 | } 34 | } 35 | } 36 | 37 | // 图是否为空 38 | if (indegree.iter().all(|&e| e == 0)) { 39 | order 40 | } else { 41 | vec![] 42 | } 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /n0213. House Robber II/README.md: -------------------------------------------------------------------------------- 1 | # House Robber II :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/house-robber-ii](https://leetcode-cn.com/problems/house-robber-ii) 3 | - 执行时间: 4 ms 4 | - 内存消耗: 2.3 MB 5 | - 通过日期: 2019-03-23 16:32 6 | 7 | ## 题目内容 8 |

你是一个专业的小偷,计划偷窃沿街的房屋,每间房内都藏有一定的现金。这个地方所有的房屋都围成一圈,这意味着第一个房屋和最后一个房屋是紧挨着的。同时,相邻的房屋装有相互连通的防盗系统,如果两间相邻的房屋在同一晚上被小偷闯入,系统会自动报警

9 | 10 |

给定一个代表每个房屋存放金额的非负整数数组,计算你在不触动警报装置的情况下,能够偷窃到的最高金额。

11 | 12 |

示例 1:

13 | 14 |
输入: [2,3,2]
15 | 输出: 3
16 | 解释: 你不能先偷窃 1 号房屋(金额 = 2),然后偷窃 3 号房屋(金额 = 2), 因为他们是相邻的。
17 | 
18 | 19 |

示例 2:

20 | 21 |
输入: [1,2,3,1]
22 | 输出: 4
23 | 解释: 你可以先偷窃 1 号房屋(金额 = 1),然后偷窃 3 号房屋(金额 = 3)。
24 |      偷窃到的最高金额 = 1 + 3 = 4 。
25 | 26 | 27 | ## 解法 28 | ```rust 29 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 30 | // Zhihu: https://www.zhihu.com/people/netcan 31 | 32 | impl Solution { 33 | pub fn rob(nums: Vec) -> i32 { 34 | if nums.len() <= 2 { return *nums.iter().max().unwrap_or(&0); } 35 | 36 | (0..=2).map(|i| { 37 | let mut vis = vec![-1; nums.len()]; // 记录偷过的最大价值? 38 | Solution::dfs(&nums, &mut vis, i, i) 39 | }).max().unwrap_or(0) 40 | } 41 | fn dfs(nums: &Vec, vis: &mut Vec, starti: usize, i: usize) -> i32 { // 从第start_i家开始偷,目前偷到第i家 42 | let n = nums.len(); 43 | if (i + 1) % n == starti { return 0; } // 偷到头了,回溯 44 | if vis[i] != -1 { return vis[i]; } 45 | 46 | let mut value = nums[i]; 47 | for step in 2..n { 48 | if (step + i) % n <= i { break; } 49 | value = value.max(nums[i] + Solution::dfs(nums, vis, starti, step + i)); 50 | } 51 | 52 | vis[i] = value; 53 | value 54 | } 55 | } 56 | 57 | 58 | ``` -------------------------------------------------------------------------------- /n0213. House Robber II/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn rob(nums: Vec) -> i32 { 6 | if nums.len() <= 2 { return *nums.iter().max().unwrap_or(&0); } 7 | 8 | (0..=2).map(|i| { 9 | let mut vis = vec![-1; nums.len()]; // 记录偷过的最大价值? 10 | Solution::dfs(&nums, &mut vis, i, i) 11 | }).max().unwrap_or(0) 12 | } 13 | fn dfs(nums: &Vec, vis: &mut Vec, starti: usize, i: usize) -> i32 { // 从第start_i家开始偷,目前偷到第i家 14 | let n = nums.len(); 15 | if (i + 1) % n == starti { return 0; } // 偷到头了,回溯 16 | if vis[i] != -1 { return vis[i]; } 17 | 18 | let mut value = nums[i]; 19 | for step in 2..n { 20 | if (step + i) % n <= i { break; } 21 | value = value.max(nums[i] + Solution::dfs(nums, vis, starti, step + i)); 22 | } 23 | 24 | vis[i] = value; 25 | value 26 | } 27 | } 28 | 29 | -------------------------------------------------------------------------------- /n0223. Rectangle Area/README.md: -------------------------------------------------------------------------------- 1 | # Rectangle Area :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/rectangle-area](https://leetcode-cn.com/problems/rectangle-area) 3 | - 执行时间: 16 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-14 23:49 6 | 7 | ## 题目内容 8 |

二维平面上计算出两个由直线构成的矩形重叠后形成的总面积。

9 | 10 |

每个矩形由其左下顶点和右上顶点坐标表示,如图所示。

11 | 12 |

Rectangle Area

13 | 14 |

示例:

15 | 16 |
输入: -3, 0, 3, 4, 0, -1, 9, 2
17 | 输出: 45
18 | 19 |

说明: 假设矩形面积不会超出 int 的范围。

20 | 21 | 22 | ## 解法 23 | ```rust 24 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 25 | // Zhihu: https://www.zhihu.com/people/netcan 26 | 27 | use std::cmp::{max, min}; 28 | impl Solution { 29 | pub fn compute_area(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) -> i32 { 30 | let (a, b, c, d, e, f, g, h): (i64, i64, i64, i64, i64, i64, i64, i64) = 31 | (a as i64, b as i64, c as i64, d as i64, e as i64, f as i64, g as i64, h as i64); 32 | // 重叠部分面积 33 | let dup_area = max(0, (min(h, d) - max(f, b))) * max(0, (min(c, g) - max(a, e))); 34 | // 两面积之和减去重叠部分 35 | ((d - b) * (c - a) + (h - f) * (g - e) - dup_area) as i32 36 | } 37 | } 38 | 39 | #[cfg(test)] 40 | mod tests { 41 | use super::*; 42 | #[test] 43 | fn test_1() { 44 | assert_eq!(Solution::compute_area(-2, -2, 2, 2, 3, 3, 4, 4), 17); 45 | } 46 | #[test] 47 | fn test_2() { 48 | assert_eq!(Solution::compute_area(-1500000001, 0, -1500000000, 1, 1500000000, 0, 1500000001, 1), 2); 49 | } 50 | } 51 | 52 | ``` -------------------------------------------------------------------------------- /n0223. Rectangle Area/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::{max, min}; 5 | impl Solution { 6 | pub fn compute_area(a: i32, b: i32, c: i32, d: i32, e: i32, f: i32, g: i32, h: i32) -> i32 { 7 | let (a, b, c, d, e, f, g, h): (i64, i64, i64, i64, i64, i64, i64, i64) = 8 | (a as i64, b as i64, c as i64, d as i64, e as i64, f as i64, g as i64, h as i64); 9 | // 重叠部分面积 10 | let dup_area = max(0, (min(h, d) - max(f, b))) * max(0, (min(c, g) - max(a, e))); 11 | // 两面积之和减去重叠部分 12 | ((d - b) * (c - a) + (h - f) * (g - e) - dup_area) as i32 13 | } 14 | } 15 | 16 | #[cfg(test)] 17 | mod tests { 18 | use super::*; 19 | #[test] 20 | fn test_1() { 21 | assert_eq!(Solution::compute_area(-2, -2, 2, 2, 3, 3, 4, 4), 17); 22 | } 23 | #[test] 24 | fn test_2() { 25 | assert_eq!(Solution::compute_area(-1500000001, 0, -1500000000, 1, 1500000000, 0, 1500000001, 1), 2); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /n0241. Different Ways to Add Parentheses/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | fn bin_op(a: i32, b: i32, o: char) -> i32 { 5 | match o { 6 | '+' => { a + b }, 7 | '-' => { a - b }, 8 | '*' => { a * b }, 9 | _ => { unreachable!() } 10 | } 11 | } 12 | 13 | impl Solution { 14 | pub fn diff_ways_to_compute(input: String) -> Vec { 15 | let numbers: Vec = input 16 | .split(|c| c == '+' || c == '-' || c == '*') 17 | .map(|x| x.parse().unwrap()) 18 | .collect(); 19 | 20 | let op: Vec = input 21 | .split(char::is_numeric) 22 | .filter(|o| o.len() > 0) 23 | .map(|o| o.as_bytes()[0] as char).collect(); 24 | 25 | println!("numbers: {:?} op: {:?}", numbers, op); 26 | Solution::diff_ways_to_compute_(&numbers, &op) 27 | } 28 | pub fn diff_ways_to_compute_(numbers: &[i32], op: &[char]) -> Vec { 29 | if numbers.len() == 1 { return vec![numbers[0]]; } 30 | 31 | let mut result = vec![]; 32 | // 计算左部分[0..j) op 右部分[j..end) 33 | let end = numbers.len(); 34 | for j in 1..end { 35 | let (left_vals, right_vals) = ( 36 | Solution::diff_ways_to_compute_(&numbers[0..j], &op[0..j-1]), 37 | Solution::diff_ways_to_compute_(&numbers[j..end], &op[j..op.len()]) 38 | ); 39 | for &lval in &left_vals { 40 | for &rval in &right_vals { 41 | result.push(bin_op(lval, rval, op[j-1])) 42 | } 43 | } 44 | } 45 | 46 | result 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /n0257. Binary Tree Paths/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | // Definition for a binary tree node. 5 | // #[derive(Debug, PartialEq, Eq)] 6 | // pub struct TreeNode { 7 | // pub val: i32, 8 | // pub left: Option>>, 9 | // pub right: Option>>, 10 | // } 11 | // 12 | // impl TreeNode { 13 | // #[inline] 14 | // pub fn new(val: i32) -> Self { 15 | // TreeNode { 16 | // val, 17 | // left: None, 18 | // right: None 19 | // } 20 | // } 21 | // } 22 | use std::rc::Rc; 23 | use std::cell::RefCell; 24 | impl Solution { 25 | pub fn binary_tree_paths(root: Option>>) -> Vec { 26 | let mut ret = vec![]; 27 | Solution::binary_tree(&root, &mut ret, &String::new()); 28 | ret 29 | } 30 | 31 | fn binary_tree(root: &Option>>, paths: &mut Vec, path: &String) { 32 | match root { 33 | Some(node) => { 34 | let node = node.borrow(); 35 | let mut path_tmp = path.clone(); 36 | if path_tmp.len() != 0 { 37 | path_tmp.push_str("->"); 38 | } 39 | path_tmp.push_str(&node.val.to_string()); 40 | if let None = node.left { 41 | if let None = node.right { 42 | paths.push(path_tmp.clone()); 43 | } 44 | } 45 | Solution::binary_tree(&node.left, paths, &path_tmp); 46 | Solution::binary_tree(&node.right, paths, &path_tmp); 47 | } 48 | _ => {} 49 | } 50 | } 51 | } 52 | 53 | 54 | -------------------------------------------------------------------------------- /n0279. Perfect Squares/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::VecDeque; 5 | use std::collections::HashMap; 6 | impl Solution { 7 | pub fn num_squares(n: i32) -> i32 { 8 | let mut square = vec![]; 9 | // 队列的层数即答案,每次入队完全平方数 10 | let mut que = VecDeque::new(); 11 | let mut mark = HashMap::::new(); 12 | 13 | for i in 1..=n { 14 | let i2 = i * i; 15 | if i2 <= n { 16 | square.push(i2); 17 | mark.insert(i2, true); 18 | que.push_back((i2, 1)); 19 | } 20 | else { break; } 21 | } 22 | 23 | while !que.is_empty() { 24 | let (num, step) = que.pop_front().unwrap(); 25 | if num == n { return step; } 26 | 27 | for sq in &square { 28 | let next_num = sq + num; 29 | if next_num > n { break; } 30 | // 根据4平方数定理,剪枝 31 | if !mark.contains_key(&next_num) && step < 4 { 32 | que.push_back((next_num, step + 1)); 33 | mark.insert(next_num, true); 34 | } 35 | } 36 | } 37 | 38 | 0 39 | } 40 | } 41 | 42 | -------------------------------------------------------------------------------- /n0295. Find Median from Data Stream/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::BTreeMap; 5 | 6 | struct MedianFinder { 7 | container: BTreeMap 8 | } 9 | 10 | impl MedianFinder { 11 | fn new() -> Self { 12 | MedianFinder{ 13 | container: BTreeMap::new() 14 | } 15 | } 16 | 17 | fn add_num(&mut self, num: i32) { 18 | *self.container.entry(num).or_insert(0) += 1; 19 | } 20 | 21 | fn find_median(&self) -> f64 { 22 | let mut iter = self.container.iter(); 23 | let n = self.container.values().sum::(); 24 | 25 | let (mut pos, mid_pos) = (-1, ((n - 1)/ 2) as i32); 26 | let mut num = 0; 27 | 28 | while pos < mid_pos { 29 | let (k, v) = iter.next().unwrap(); 30 | let times = *v; 31 | num = *k; 32 | if pos + times > mid_pos { 33 | return num as f64; 34 | } 35 | pos += times; 36 | } 37 | 38 | if n % 2 == 0 { 39 | (num + *iter.next().unwrap().0) as f64 / 2.0 40 | } else { 41 | num as f64 42 | } 43 | } 44 | } 45 | 46 | -------------------------------------------------------------------------------- /n0300. Longest Increasing Subsequence/README.md: -------------------------------------------------------------------------------- 1 | # Longest Increasing Subsequence :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/longest-increasing-subsequence](https://leetcode-cn.com/problems/longest-increasing-subsequence) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-20 19:15 6 | 7 | ## 题目内容 8 |

给定一个无序的整数数组,找到其中最长上升子序列的长度。

9 | 10 |

示例:

11 | 12 |
输入: [10,9,2,5,3,7,101,18]
13 | 输出: 4 
14 | 解释: 最长的上升子序列是 [2,3,7,101],它的长度是 4
15 | 16 |

说明:

17 | 18 |
    19 |
  • 可能会有多种最长上升子序列的组合,你只需要输出对应的长度即可。
  • 20 |
  • 你算法的时间复杂度应该为 O(n2) 。
  • 21 |
22 | 23 |

进阶: 你能将算法的时间复杂度降低到 O(n log n) 吗?

24 | 25 | 26 | ## 解法 27 | ```rust 28 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 29 | // Zhihu: https://www.zhihu.com/people/netcan 30 | 31 | impl Solution { 32 | pub fn length_of_lis(nums: Vec) -> i32 { 33 | let mut longest = Vec::with_capacity(nums.len()); 34 | 35 | for num in nums { 36 | match longest.binary_search(&num) { 37 | Err(pos) => { 38 | if pos < longest.len() { 39 | longest[pos] = num; 40 | } else { 41 | longest.push(num); 42 | } 43 | }, 44 | _ => {} 45 | } 46 | } 47 | 48 | longest.len() as i32 49 | } 50 | } 51 | 52 | 53 | ``` -------------------------------------------------------------------------------- /n0300. Longest Increasing Subsequence/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn length_of_lis(nums: Vec) -> i32 { 6 | let mut longest = Vec::with_capacity(nums.len()); 7 | 8 | for num in nums { 9 | match longest.binary_search(&num) { 10 | Err(pos) => { 11 | if pos < longest.len() { 12 | longest[pos] = num; 13 | } else { 14 | longest.push(num); 15 | } 16 | }, 17 | _ => {} 18 | } 19 | } 20 | 21 | longest.len() as i32 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /n0312. Burst Balloons/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | impl Solution { 6 | pub fn max_coins(mut nums: Vec) -> i32 { 7 | // dp[i][j]: 从i到j获得的最大硬币数量 8 | // coin[k]: 戳爆第k个气球得分 9 | // dp[i][j] = max(dp[i][j], dp[i][k - 1] + coin[i-1]*coin[k]*coin[j+1] + dp[k+1][j]) 10 | let n = nums.len(); 11 | if n == 0 { return 0; } 12 | else if n == 1 { return nums[0]; } 13 | 14 | let mut coin = vec![1]; coin.append(&mut nums); coin.push(1); 15 | 16 | let mut dp:Vec> = 17 | iter::repeat(vec![0; n + 1]).take(n + 1).collect(); 18 | for i in 1..=n { dp[i][i] = coin[i-1] * coin[i] * coin[i+1]; } 19 | 20 | for step in 1..n { 21 | for i in 1..=n-step { 22 | let j = i + step; 23 | for k in i..=j { 24 | let left = if k - 1 < i { 0 } else { dp[i][k - 1] }; 25 | let right = if k + 1 > j { 0 } else { dp[k + 1][j] }; 26 | dp[i][j] = dp[i][j].max(left + right + coin[i-1] * coin[k] * coin[j+1]); 27 | } 28 | } 29 | } 30 | dp[1][n] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /n0315. Count of Smaller Numbers After Self/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn count_smaller(nums: Vec) -> Vec { 6 | fn merged_sort(nums: &mut [(usize, i32)], counts: &mut Vec) -> Vec<(usize, i32)> { 7 | let n = nums.len(); 8 | if n <= 1 { return vec![nums[0]]; } 9 | let (left, right) = nums.split_at_mut(n / 2); 10 | 11 | let left = merged_sort(left, counts); 12 | let right = merged_sort(right, counts); 13 | let (m, n) = (left.len(), right.len()); 14 | let mut sorted = vec![(0, 0); left.len() + right.len()]; 15 | let (mut i, mut j) = (0, 0); 16 | 17 | while i < m || j < n { 18 | if j == n || (i < m && left[i].1 <= right[j].1) { 19 | sorted[i + j] = left[i]; 20 | counts[left[i].0] += j as i32; // 位于右边的数排到左边的都是小于这个数 21 | i += 1; 22 | } else { 23 | sorted[i + j] = right[j]; 24 | j += 1; 25 | } 26 | } 27 | sorted 28 | } 29 | 30 | let n = nums.len(); 31 | let mut counts = vec![0; n]; 32 | if n == 0 { return counts; } 33 | merged_sort(&mut nums.into_iter().enumerate().collect::>(), &mut counts); 34 | 35 | counts 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /n0322. Coin Change/README.md: -------------------------------------------------------------------------------- 1 | # Coin Change :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/coin-change](https://leetcode-cn.com/problems/coin-change) 3 | - 执行时间: 12 ms 4 | - 内存消耗: 3 MB 5 | - 通过日期: 2019-04-04 11:37 6 | 7 | ## 题目内容 8 |

给定不同面额的硬币 coins 和一个总金额 amount。编写一个函数来计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1

9 | 10 |

示例 1:

11 | 12 |
输入: coins = [1, 2, 5], amount = 11
13 | 输出: 3 
14 | 解释: 11 = 5 + 5 + 1
15 | 16 |

示例 2:

17 | 18 |
输入: coins = [2], amount = 3
19 | 输出: -1
20 | 21 |

说明:
22 | 你可以认为每种硬币的数量是无限的。

23 | 24 | 25 | ## 解法 26 | ```rust 27 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 28 | // Zhihu: https://www.zhihu.com/people/netcan 29 | 30 | impl Solution { 31 | pub fn coin_change(coins: Vec, amount: i32) -> i32 { 32 | // dp[m]: 凑到金额m所需要的最少金币数 33 | // dp[m] = min(dp[m - coins[i]] + 1, dp[m]), dp[coins[i]] = 1 34 | if amount == 0 { return 0; } 35 | let mut dp = vec![amount + 1; amount as usize + 1]; 36 | for c in &coins { 37 | if *c <= amount { dp[*c as usize] = 1; } 38 | } 39 | 40 | for i in 0..coins.len() { 41 | for m in coins[i]..=amount { 42 | dp[m as usize] = dp[m as usize].min(dp[(m - coins[i]) as usize] + 1); 43 | } 44 | } 45 | 46 | if dp[amount as usize] > amount { -1 } 47 | else { dp[amount as usize] } 48 | } 49 | } 50 | 51 | 52 | ``` -------------------------------------------------------------------------------- /n0322. Coin Change/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn coin_change(coins: Vec, amount: i32) -> i32 { 6 | // dp[m]: 凑到金额m所需要的最少金币数 7 | // dp[m] = min(dp[m - coins[i]] + 1, dp[m]), dp[coins[i]] = 1 8 | if amount == 0 { return 0; } 9 | let mut dp = vec![amount + 1; amount as usize + 1]; 10 | for c in &coins { 11 | if *c <= amount { dp[*c as usize] = 1; } 12 | } 13 | 14 | for i in 0..coins.len() { 15 | for m in coins[i]..=amount { 16 | dp[m as usize] = dp[m as usize].min(dp[(m - coins[i]) as usize] + 1); 17 | } 18 | } 19 | 20 | if dp[amount as usize] > amount { -1 } 21 | else { dp[amount as usize] } 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /n0327. Count of Range Sum/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn count_range_sum(nums: Vec, lower: i32, upper: i32) -> i32 { 6 | fn count_range_sum_(sum: &mut [i64], lower: i32, upper: i32) -> i32 { 7 | let n = sum.len(); 8 | if n <= 1 { return 0; } 9 | 10 | let (left, right) = sum.split_at_mut(n / 2); 11 | let mut count = count_range_sum_(left, lower, upper) + 12 | count_range_sum_(right, lower, upper); 13 | 14 | let (mut j, mut k) = (0, 0); 15 | for i in 0..n/2 { 16 | while j < right.len() && right[j] - left[i] < lower as i64 { j += 1; } 17 | while k < right.len() && right[k] - left[i] <= upper as i64 { k += 1; } 18 | count += k as i32 - j as i32; // 求出位于[lower, upper]的个数 19 | } 20 | sum.sort(); // 归并排序 left + right 21 | count 22 | } 23 | 24 | let mut cnt = 0; 25 | let mut pre_sum = vec![0i64; nums.len() + 1]; 26 | for (i, num) in nums.iter().enumerate() { 27 | pre_sum[i + 1] = pre_sum[i] + *num as i64; 28 | } 29 | if nums.len() >= 1 { cnt = count_range_sum_(&mut pre_sum, lower, upper); } 30 | cnt 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /n0334. Increasing Triplet Subsequence/README.md: -------------------------------------------------------------------------------- 1 | # Increasing Triplet Subsequence :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/increasing-triplet-subsequence](https://leetcode-cn.com/problems/increasing-triplet-subsequence) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-20 20:03 6 | 7 | ## 题目内容 8 |

给定一个未排序的数组,判断这个数组中是否存在长度为 3 的递增子序列。

9 | 10 |

数学表达式如下:

11 | 12 |
如果存在这样的 i, j, k,  且满足 0 ≤ i < j < kn-1,
13 | 使得 arr[i] < arr[j] < arr[k] ,返回 true ; 否则返回 false 。
14 | 15 |

说明: 要求算法的时间复杂度为 O(n),空间复杂度为 O(1) 。

16 | 17 |

示例 1:

18 | 19 |
输入: [1,2,3,4,5]
20 | 输出: true
21 | 
22 | 23 |

示例 2:

24 | 25 |
输入: [5,4,3,2,1]
26 | 输出: false
27 | 28 | 29 | ## 解法 30 | ```rust 31 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 32 | // Zhihu: https://www.zhihu.com/people/netcan 33 | 34 | impl Solution { 35 | pub fn increasing_triplet(nums: Vec) -> bool { 36 | if nums.len() < 3 { return false; } 37 | let mut increasing = [i32::max_value(); 3]; // O(1) space 38 | 39 | for num in nums { 40 | match increasing.binary_search(&num) { 41 | Err(pos) => { 42 | if pos >= 2 { return true; } 43 | increasing[pos] = num; 44 | }, 45 | _ => {} 46 | } 47 | } 48 | false 49 | } 50 | } 51 | 52 | 53 | ``` -------------------------------------------------------------------------------- /n0334. Increasing Triplet Subsequence/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn increasing_triplet(nums: Vec) -> bool { 6 | if nums.len() < 3 { return false; } 7 | let mut increasing = [i32::max_value(); 3]; // O(1) space 8 | 9 | for num in nums { 10 | match increasing.binary_search(&num) { 11 | Err(pos) => { 12 | if pos >= 2 { return true; } 13 | increasing[pos] = num; 14 | }, 15 | _ => {} 16 | } 17 | } 18 | false 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /n0337. House Robber III/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn rob(root: Option>>) -> i32 { 8 | fn rob_(root: &Option>>) -> (i32, i32) { 9 | match root { 10 | Some(node) => { 11 | let node = node.borrow(); 12 | let (left_rob, left_not_rob) = rob_(&node.left); 13 | let (right_rob, right_not_rob) = rob_(&node.right); 14 | (node.val + left_not_rob + right_not_rob, // rob this node 15 | left_rob.max(left_not_rob) + right_rob.max(right_not_rob)) // not rob this node 16 | }, 17 | None => { 18 | (0, 0) 19 | } 20 | } 21 | } 22 | 23 | let (root_rob, root_not_rob) = rob_(&root); 24 | root_rob.max(root_not_rob) 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /n0343. Integer Break/README.md: -------------------------------------------------------------------------------- 1 | # Integer Break :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/integer-break](https://leetcode-cn.com/problems/integer-break) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-07 15:06 6 | 7 | ## 题目内容 8 |

给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。

9 | 10 |

示例 1:

11 | 12 |
输入: 2
13 | 输出: 1
14 | 解释: 2 = 1 + 1, 1 × 1 = 1。
15 | 16 |

示例 2:

17 | 18 |
输入: 10
19 | 输出: 36
20 | 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。
21 | 22 |

说明: 你可以假设 不小于 2 且不大于 58。

23 | 24 | 25 | ## 解法 26 | ```rust 27 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 28 | // Zhihu: https://www.zhihu.com/people/netcan 29 | 30 | use std::cmp::max; 31 | impl Solution { 32 | pub fn integer_break(n: i32) -> i32 { 33 | let n: usize = n as usize; 34 | let mut dp = [0; 60]; 35 | for x in (2..=n) { 36 | for i in (1..=x/2) { 37 | let j = x - i; 38 | dp[x] = max(dp[x], max(max(max(i * j, dp[i] * dp[j]), dp[i] * j), i * dp[j])); 39 | } 40 | } 41 | dp[n] as i32 42 | } 43 | } 44 | 45 | 46 | ``` -------------------------------------------------------------------------------- /n0343. Integer Break/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::max; 5 | impl Solution { 6 | pub fn integer_break(n: i32) -> i32 { 7 | let n: usize = n as usize; 8 | let mut dp = [0; 60]; 9 | for x in (2..=n) { 10 | for i in (1..=x/2) { 11 | let j = x - i; 12 | dp[x] = max(dp[x], max(max(max(i * j, dp[i] * dp[j]), dp[i] * j), i * dp[j])); 13 | } 14 | } 15 | dp[n] as i32 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /n0349. Intersection of Two Arrays/README.md: -------------------------------------------------------------------------------- 1 | # Intersection of Two Arrays :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/intersection-of-two-arrays](https://leetcode-cn.com/problems/intersection-of-two-arrays) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-08 11:43 6 | 7 | ## 题目内容 8 |

给定两个数组,编写一个函数来计算它们的交集。

9 | 10 |

示例 1:

11 | 12 |
输入: nums1 = [1,2,2,1], nums2 = [2,2]
13 | 输出: [2]
14 | 
15 | 16 |

示例 2:

17 | 18 |
输入: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
19 | 输出: [9,4]
20 | 21 |

说明:

22 | 23 |
    24 |
  • 输出结果中的每个元素一定是唯一的。
  • 25 |
  • 我们可以不考虑输出结果的顺序。
  • 26 |
27 | 28 | 29 | ## 解法 30 | ```rust 31 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 32 | // Zhihu: https://www.zhihu.com/people/netcan 33 | 34 | use std::collections::HashSet; 35 | impl Solution { 36 | pub fn intersection(nums1: Vec, nums2: Vec) -> Vec { 37 | let a: HashSet = nums1.iter().cloned().collect(); 38 | let b: HashSet = nums2.iter().cloned().collect(); 39 | 40 | a.intersection(&b).cloned().collect() 41 | } 42 | } 43 | 44 | ``` -------------------------------------------------------------------------------- /n0349. Intersection of Two Arrays/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::HashSet; 5 | impl Solution { 6 | pub fn intersection(nums1: Vec, nums2: Vec) -> Vec { 7 | let a: HashSet = nums1.iter().cloned().collect(); 8 | let b: HashSet = nums2.iter().cloned().collect(); 9 | 10 | a.intersection(&b).cloned().collect() 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /n0354. Russian Doll Envelopes/README.md: -------------------------------------------------------------------------------- 1 | # Russian Doll Envelopes :star::star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/russian-doll-envelopes](https://leetcode-cn.com/problems/russian-doll-envelopes) 3 | - 执行时间: 8 ms 4 | - 内存消耗: 3.3 MB 5 | - 通过日期: 2019-03-21 18:49 6 | 7 | ## 题目内容 8 |

给定一些标记了宽度和高度的信封,宽度和高度以整数对形式 (w, h) 出现。当另一个信封的宽度和高度都比这个信封大的时候,这个信封就可以放进另一个信封里,如同俄罗斯套娃一样。

9 | 10 |

请计算最多能有多少个信封能组成一组“俄罗斯套娃”信封(即可以把一个信封放到另一个信封里面)。

11 | 12 |

说明:
13 | 不允许旋转信封。

14 | 15 |

示例:

16 | 17 |
输入: envelopes = [[5,4],[6,4],[6,7],[2,3]]
18 | 输出: 3 
19 | 解释: 最多信封的个数为 3, 组合为: [2,3] => [5,4] => [6,7]。
20 | 
21 | 22 | 23 | ## 解法 24 | ```rust 25 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 26 | // Zhihu: https://www.zhihu.com/people/netcan 27 | 28 | impl Solution { 29 | pub fn max_envelopes(mut envelopes: Vec>) -> i32 { 30 | // 按宽度升序排,高度降序排,然后对高度求LIS 31 | if envelopes.len() <= 0 { return 0; } 32 | envelopes.sort_by(|a, b| { 33 | if a[0] != b[0] { return a[0].cmp(&b[0]); } 34 | return b[1].cmp(&a[1]); 35 | }); 36 | 37 | let mut longest = Vec::with_capacity(envelopes.len()); 38 | for envelope in envelopes { 39 | match longest.binary_search(&envelope[1]) { 40 | Err(pos) => { 41 | if pos < longest.len() { 42 | longest[pos] = envelope[1]; 43 | } else { 44 | longest.push(envelope[1]); 45 | } 46 | }, 47 | _ => {} 48 | } 49 | } 50 | 51 | longest.len() as i32 52 | } 53 | } 54 | 55 | 56 | ``` -------------------------------------------------------------------------------- /n0354. Russian Doll Envelopes/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn max_envelopes(mut envelopes: Vec>) -> i32 { 6 | // 按宽度升序排,高度降序排,然后对高度求LIS 7 | if envelopes.len() <= 0 { return 0; } 8 | envelopes.sort_by(|a, b| { 9 | if a[0] != b[0] { return a[0].cmp(&b[0]); } 10 | return b[1].cmp(&a[1]); 11 | }); 12 | 13 | let mut longest = Vec::with_capacity(envelopes.len()); 14 | for envelope in envelopes { 15 | match longest.binary_search(&envelope[1]) { 16 | Err(pos) => { 17 | if pos < longest.len() { 18 | longest[pos] = envelope[1]; 19 | } else { 20 | longest.push(envelope[1]); 21 | } 22 | }, 23 | _ => {} 24 | } 25 | } 26 | 27 | longest.len() as i32 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /n0375. Guess Number Higher or Lower II/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | impl Solution { 6 | pub fn get_money_amount(n: i32) -> i32 { 7 | // dp[i][j]: i到j的最小代价 8 | // dp[i][j] = min(k + max(dp[i][k-1], dp[k+1][j])) for k in i..j 9 | // dp[i][i+1] = i 10 | 11 | let n: usize = n as usize; 12 | let mut dp: Vec> = 13 | iter::repeat(vec![0; n as usize + 1]) 14 | .take(n as usize + 1).collect(); 15 | 16 | for i in 1..n { dp[i][i+1] = i as i32; } 17 | 18 | for step in 1..n { 19 | for i in 1..=n - step { 20 | let j = i + step; 21 | let mut min_money = -1; 22 | for k in i+1..j { 23 | let money = k as i32 + dp[i][k-1].max(dp[k+1][j]); 24 | if min_money == -1 || min_money > money { min_money = money; } 25 | } 26 | if min_money != -1 { dp[i][j] = min_money; } 27 | } 28 | } 29 | 30 | dp[1][n] 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /n0383. Ransom Note/README.md: -------------------------------------------------------------------------------- 1 | # Ransom Note :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/ransom-note](https://leetcode-cn.com/problems/ransom-note) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.8 MB 5 | - 通过日期: 2019-03-20 14:43 6 | 7 | ## 题目内容 8 |

给定一个赎金信 (ransom) 字符串和一个杂志(magazine)字符串,判断第一个字符串ransom能不能由第二个字符串magazines里面的字符构成。如果可以构成,返回 true ;否则返回 false。

9 | 10 |

(题目说明:为了不暴露赎金信字迹,要从杂志上搜索各个需要的字母,组成单词来表达意思。)

11 | 12 |

注意:

13 | 14 |

你可以假设两个字符串均只含有小写字母。

15 | 16 |
17 | canConstruct("a", "b") -> false
18 | canConstruct("aa", "ab") -> false
19 | canConstruct("aa", "aab") -> true
20 | 
21 | 22 | 23 | ## 解法 24 | ```rust 25 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 26 | // Zhihu: https://www.zhihu.com/people/netcan 27 | 28 | use std::collections::HashMap; 29 | impl Solution { 30 | pub fn can_construct(ransom_note: String, magazine: String) -> bool { 31 | let ransom_note = ransom_note.into_bytes(); 32 | let mut magazine = magazine.into_bytes(); 33 | for cr in ransom_note { 34 | let mut find = false; 35 | for (j, &cm) in magazine.iter().enumerate() { 36 | if cr == cm { 37 | find = true; 38 | magazine.remove(j); 39 | break; 40 | } 41 | } 42 | if !find { 43 | return false; 44 | } 45 | } 46 | 47 | true 48 | } 49 | } 50 | 51 | 52 | ``` -------------------------------------------------------------------------------- /n0383. Ransom Note/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::HashMap; 5 | impl Solution { 6 | pub fn can_construct(ransom_note: String, magazine: String) -> bool { 7 | let ransom_note = ransom_note.into_bytes(); 8 | let mut magazine = magazine.into_bytes(); 9 | for cr in ransom_note { 10 | let mut find = false; 11 | for (j, &cm) in magazine.iter().enumerate() { 12 | if cr == cm { 13 | find = true; 14 | magazine.remove(j); 15 | break; 16 | } 17 | } 18 | if !find { 19 | return false; 20 | } 21 | } 22 | 23 | true 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /n0392. Is Subsequence/README.md: -------------------------------------------------------------------------------- 1 | # Is Subsequence :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/is-subsequence](https://leetcode-cn.com/problems/is-subsequence) 3 | - 执行时间: 4 ms 4 | - 内存消耗: 4.6 MB 5 | - 通过日期: 2019-03-15 10:02 6 | 7 | ## 题目内容 8 |

给定字符串 st ,判断 s 是否为 t 的子序列。

9 | 10 |

你可以认为 st 中仅包含英文小写字母。字符串 t 可能会很长(长度 ~= 500,000),而 s 是个短字符串(长度 <=100)。

11 | 12 |

字符串的一个子序列是原始字符串删除一些(也可以不删除)字符而不改变剩余字符相对位置形成的新字符串。(例如,"ace""abcde"的一个子序列,而"aec"不是)。

13 | 14 |

示例 1:
15 | s = "abc", t = "ahbgdc"

16 | 17 |

返回 true.

18 | 19 |

示例 2:
20 | s = "axc", t = "ahbgdc"

21 | 22 |

返回 false.

23 | 24 |

后续挑战 :

25 | 26 |

如果有大量输入的 S,称作S1, S2, ... , Sk 其中 k >= 10亿,你需要依次检查它们是否为 T 的子序列。在这种情况下,你会怎样改变代码?

27 | 28 |

致谢:

29 | 30 |

特别感谢 @pbrother 添加此问题并且创建所有测试用例。

31 | 32 | 33 | ## 解法 34 | ```rust 35 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 36 | // Zhihu: https://www.zhihu.com/people/netcan 37 | 38 | impl Solution { 39 | pub fn is_subsequence(s: String, t: String) -> bool { 40 | if s.len() == 0 { return true; } 41 | let (s, t) = (s.into_bytes(), t.into_bytes()); 42 | let (mut i, mut j) = (0, 0); 43 | while i < s.len() && j < t.len() { 44 | if s[i] == t[j] { 45 | i += 1; 46 | if i == s.len() { return true; } 47 | } 48 | j += 1; 49 | } 50 | false 51 | } 52 | } 53 | 54 | 55 | ``` -------------------------------------------------------------------------------- /n0392. Is Subsequence/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn is_subsequence(s: String, t: String) -> bool { 6 | if s.len() == 0 { return true; } 7 | let (s, t) = (s.into_bytes(), t.into_bytes()); 8 | let (mut i, mut j) = (0, 0); 9 | while i < s.len() && j < t.len() { 10 | if s[i] == t[j] { 11 | i += 1; 12 | if i == s.len() { return true; } 13 | } 14 | j += 1; 15 | } 16 | false 17 | } 18 | } 19 | 20 | -------------------------------------------------------------------------------- /n0401. Binary Watch/README.md: -------------------------------------------------------------------------------- 1 | # Binary Watch :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/binary-watch](https://leetcode-cn.com/problems/binary-watch) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-04-20 16:47 6 | 7 | ## 题目内容 8 |

二进制手表顶部有 4 个 LED 代表小时(0-11),底部的 6 个 LED 代表分钟(0-59)

9 | 10 |

每个 LED 代表一个 0 或 1,最低位在右侧。

11 | 12 |

13 | 14 |

例如,上面的二进制手表读取 “3:25”。

15 | 16 |

给定一个非负整数 代表当前 LED 亮着的数量,返回所有可能的时间。

17 | 18 |

案例:

19 | 20 |
21 | 输入: n = 1
22 | 返回: ["1:00", "2:00", "4:00", "8:00", "0:01", "0:02", "0:04", "0:08", "0:16", "0:32"]
23 | 24 | 25 | 26 |

注意事项:

27 | 28 |
    29 |
  • 输出的顺序没有要求。
  • 30 |
  • 小时不会以零开头,比如 “01:00” 是不允许的,应为 “1:00”。
  • 31 |
  • 分钟必须由两位数组成,可能会以零开头,比如 “10:2” 是无效的,应为 “10:02”。
  • 32 |
33 | 34 | 35 | ## 解法 36 | ```rust 37 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 38 | // Zhihu: https://www.zhihu.com/people/netcan 39 | 40 | impl Solution { 41 | pub fn read_binary_watch(num: i32) -> Vec { 42 | let mut watch = vec![]; 43 | for led in 0..1<<10 { 44 | let (mut led_num, mut led_) = (0, led); 45 | while led_ > 0 { 46 | led_ &= led_ - 1; 47 | led_num += 1; 48 | } 49 | 50 | if led_num == num { 51 | let (hour, min) = (led >> 6, led & 0x3f); 52 | if hour < 12 && min < 60 { 53 | watch.push(format!("{}:{:02}", led >> 6, led & 0x3f)) 54 | } 55 | } 56 | } 57 | 58 | watch 59 | } 60 | } 61 | 62 | 63 | ``` -------------------------------------------------------------------------------- /n0401. Binary Watch/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn read_binary_watch(num: i32) -> Vec { 6 | let mut watch = vec![]; 7 | for led in 0..1<<10 { 8 | let (mut led_num, mut led_) = (0, led); 9 | while led_ > 0 { 10 | led_ &= led_ - 1; 11 | led_num += 1; 12 | } 13 | 14 | if led_num == num { 15 | let (hour, min) = (led >> 6, led & 0x3f); 16 | if hour < 12 && min < 60 { 17 | watch.push(format!("{}:{:02}", led >> 6, led & 0x3f)) 18 | } 19 | } 20 | } 21 | 22 | watch 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /n0405. Convert a Number to Hexadecimal/README.md: -------------------------------------------------------------------------------- 1 | # Convert a Number to Hexadecimal :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal](https://leetcode-cn.com/problems/convert-a-number-to-hexadecimal) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.3 MB 5 | - 通过日期: 2019-03-06 09:52 6 | 7 | ## 题目内容 8 |

给定一个整数,编写一个算法将这个数转换为十六进制数。对于负整数,我们通常使用 补码运算 方法。

9 | 10 |

注意:

11 | 12 |
    13 |
  1. 十六进制中所有字母(a-f)都必须是小写。
  2. 14 |
  3. 十六进制字符串中不能包含多余的前导零。如果要转化的数为0,那么以单个字符'0'来表示;对于其他情况,十六进制字符串中的第一个字符将不会是0字符。 
  4. 15 |
  5. 给定的数确保在32位有符号整数范围内。
  6. 16 |
  7. 不能使用任何由库提供的将数字直接转换或格式化为十六进制的方法。
  8. 17 |
18 | 19 |

示例 1:

20 | 21 |
22 | 输入:
23 | 26
24 | 
25 | 输出:
26 | "1a"
27 | 
28 | 29 |

示例 2:

30 | 31 |
32 | 输入:
33 | -1
34 | 
35 | 输出:
36 | "ffffffff"
37 | 
38 | 39 | 40 | ## 解法 41 | ```rust 42 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 43 | // Zhihu: https://www.zhihu.com/people/netcan 44 | 45 | impl Solution { 46 | const H:[char;16] = [ 47 | '0', '1', '2', '3', '4', '5', 48 | '6', '7', '8', '9', 'a', 'b', 49 | 'c', 'd', 'e', 'f' 50 | ]; 51 | pub fn to_hex(num: i32) -> String { 52 | let mut num = num as u32; 53 | if num == 0 { 54 | return "0".to_owned(); 55 | } 56 | let mut ret = String::new(); 57 | while num > 0 { 58 | ret.push(Solution::H[(num % 16) as usize]); 59 | num /= 16; 60 | } 61 | ret.chars().rev().collect() 62 | } 63 | } 64 | 65 | 66 | ``` -------------------------------------------------------------------------------- /n0405. Convert a Number to Hexadecimal/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | const H:[char;16] = [ 6 | '0', '1', '2', '3', '4', '5', 7 | '6', '7', '8', '9', 'a', 'b', 8 | 'c', 'd', 'e', 'f' 9 | ]; 10 | pub fn to_hex(num: i32) -> String { 11 | let mut num = num as u32; 12 | if num == 0 { 13 | return "0".to_owned(); 14 | } 15 | let mut ret = String::new(); 16 | while num > 0 { 17 | ret.push(Solution::H[(num % 16) as usize]); 18 | num /= 16; 19 | } 20 | ret.chars().rev().collect() 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /n0424. Longest Repeating Character Replacement/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::VecDeque; 5 | use std::collections::HashSet; 6 | use std::iter::FromIterator; 7 | impl Solution { 8 | pub fn character_replacement(s: String, k: i32) -> i32 { 9 | let s = s.into_bytes(); 10 | let chars: HashSet = HashSet::from_iter(s.iter().cloned()); 11 | let mut ans = 0; 12 | for c in &chars { 13 | ans = ans.max( 14 | Solution::longest_character_replacement(&s, *c, k) 15 | ); 16 | } 17 | ans 18 | } 19 | 20 | fn longest_character_replacement(s: &Vec, c: u8, k: i32) -> i32 { 21 | let mut replace_chars = VecDeque::new(); 22 | let mut length = 0; 23 | let mut i = 0; 24 | for j in 0..s.len() { 25 | if s[j] != c { 26 | replace_chars.push_back(j); 27 | if replace_chars.len() > k as usize { 28 | i = replace_chars.pop_front().unwrap() + 1; 29 | } 30 | } 31 | length = length.max(j - i + 1); 32 | } 33 | 34 | length as i32 35 | } 36 | } 37 | 38 | -------------------------------------------------------------------------------- /n0437. Path Sum III/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | 7 | impl Solution { 8 | pub fn path_sum(root: Option>>, sum: i32) -> i32 { 9 | let mut cnt = 0; 10 | Solution::traverse(&root, sum, &mut cnt); 11 | cnt 12 | } 13 | 14 | fn traverse(root: &Option>>, sum: i32, count: &mut i32) { 15 | if let Some(node) = root { 16 | let node = node.borrow(); 17 | Solution::path_sum_(&root, sum, count); 18 | Solution::traverse(&node.left, sum, count); 19 | Solution::traverse(&node.right, sum, count); 20 | } 21 | } 22 | 23 | fn path_sum_(root: &Option>>, sum: i32, count: &mut i32) { 24 | match root { 25 | Some(node) => { 26 | let node = node.borrow(); 27 | let diff = sum - node.val; 28 | if diff == 0 { *count += 1; } 29 | Solution::path_sum_(&node.left, diff, count); 30 | Solution::path_sum_(&node.right, diff, count); 31 | }, 32 | None => {} 33 | } 34 | } 35 | 36 | } 37 | 38 | -------------------------------------------------------------------------------- /n0443. String Compression/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn compress(chars: &mut Vec) -> i32 { 6 | let mut repeat_num = 1; 7 | let mut i = 1; 8 | while i < chars.len() { 9 | if chars[i - 1] == chars[i] { 10 | repeat_num += 1; 11 | } else { 12 | if repeat_num >= 2 { 13 | let repeat_num_char = repeat_num.to_string(); 14 | chars.splice((i - repeat_num + 1)..i, repeat_num_char.chars()); 15 | i = i - repeat_num + 1 + repeat_num_char.len(); 16 | } 17 | repeat_num = 1; 18 | } 19 | i += 1; 20 | } 21 | 22 | if repeat_num >= 2 { 23 | chars.splice((chars.len() - repeat_num + 1)..chars.len(), repeat_num.to_string().chars()); 24 | } 25 | 26 | chars.len() as i32 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /n0455. Assign Cookies/README.md: -------------------------------------------------------------------------------- 1 | # Assign Cookies :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/assign-cookies](https://leetcode-cn.com/problems/assign-cookies) 3 | - 执行时间: 12 ms 4 | - 内存消耗: 3.1 MB 5 | - 通过日期: 2019-03-05 20:22 6 | 7 | ## 题目内容 8 |

假设你是一位很棒的家长,想要给你的孩子们一些小饼干。但是,每个孩子最多只能给一块饼干。对每个孩子 i ,都有一个胃口值 gi ,这是能让孩子们满足胃口的饼干的最小尺寸;并且每块饼干 j ,都有一个尺寸 s。如果 sj >= g,我们可以将这个饼干 j 分配给孩子 i ,这个孩子会得到满足。你的目标是尽可能满足越多数量的孩子,并输出这个最大数值。

9 | 10 |

注意:

11 | 12 |

你可以假设胃口值为正。
13 | 一个小朋友最多只能拥有一块饼干。

14 | 15 |

示例 1:

16 | 17 |
18 | 输入: [1,2,3], [1,1]
19 | 
20 | 输出: 1
21 | 
22 | 解释: 
23 | 你有三个孩子和两块小饼干,3个孩子的胃口值分别是:1,2,3。
24 | 虽然你有两块小饼干,由于他们的尺寸都是1,你只能让胃口值是1的孩子满足。
25 | 所以你应该输出1。
26 | 
27 | 28 |

示例 2:

29 | 30 |
31 | 输入: [1,2], [1,2,3]
32 | 
33 | 输出: 2
34 | 
35 | 解释: 
36 | 你有两个孩子和三块小饼干,2个孩子的胃口值分别是1,2。
37 | 你拥有的饼干数量和尺寸都足以让所有孩子满足。
38 | 所以你应该输出2.
39 | 
40 | 41 | 42 | ## 解法 43 | ```rust 44 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 45 | // Zhihu: https://www.zhihu.com/people/netcan 46 | 47 | impl Solution { 48 | pub fn find_content_children(mut g: Vec, mut s: Vec) -> i32 { 49 | g.sort(); 50 | s.sort(); 51 | 52 | let mut ret = 0; 53 | let mut j = 0; 54 | for ss in &s { 55 | if j >= g.len() { 56 | break; 57 | } 58 | if *ss >= g[j] { 59 | ret += 1; 60 | j += 1; 61 | } 62 | } 63 | 64 | ret 65 | } 66 | } 67 | 68 | 69 | 70 | ``` -------------------------------------------------------------------------------- /n0455. Assign Cookies/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn find_content_children(mut g: Vec, mut s: Vec) -> i32 { 6 | g.sort(); 7 | s.sort(); 8 | 9 | let mut ret = 0; 10 | let mut j = 0; 11 | for ss in &s { 12 | if j >= g.len() { 13 | break; 14 | } 15 | if *ss >= g[j] { 16 | ret += 1; 17 | j += 1; 18 | } 19 | } 20 | 21 | ret 22 | } 23 | } 24 | 25 | 26 | -------------------------------------------------------------------------------- /n0461. Hamming Distance/README.md: -------------------------------------------------------------------------------- 1 | # Hamming Distance :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/hamming-distance](https://leetcode-cn.com/problems/hamming-distance) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-08 14:38 6 | 7 | ## 题目内容 8 |

两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

9 | 10 |

给出两个整数 xy,计算它们之间的汉明距离。

11 | 12 |

注意:
13 | 0 ≤ x, y < 231.

14 | 15 |

示例:

16 | 17 |
18 | 输入: x = 1, y = 4
19 | 
20 | 输出: 2
21 | 
22 | 解释:
23 | 1   (0 0 0 1)
24 | 4   (0 1 0 0)
25 |        ↑   ↑
26 | 
27 | 上面的箭头指出了对应二进制位不同的位置。
28 | 
29 | 30 | 31 | ## 解法 32 | ```rust 33 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 34 | // Zhihu: https://www.zhihu.com/people/netcan 35 | 36 | impl Solution { 37 | pub fn hamming_distance(x: i32, y: i32) -> i32 { 38 | let mut v = x ^ y; 39 | let mut ret = 0; 40 | while v > 0 { 41 | if v & 1 == 1 { 42 | ret += 1; 43 | } 44 | v >>= 1; 45 | } 46 | ret 47 | } 48 | } 49 | 50 | 51 | ``` -------------------------------------------------------------------------------- /n0461. Hamming Distance/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn hamming_distance(x: i32, y: i32) -> i32 { 6 | let mut v = x ^ y; 7 | let mut ret = 0; 8 | while v > 0 { 9 | if v & 1 == 1 { 10 | ret += 1; 11 | } 12 | v >>= 1; 13 | } 14 | ret 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /n0463. Island Perimeter/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | const dxy: [(i32, i32); 4] = [(0 ,1), (0, -1), (-1, 0), (1, 0)]; 6 | pub fn island_perimeter(grid: Vec>) -> i32 { 7 | let mut p = 0; 8 | 9 | for j in 0..grid.len() { 10 | for i in 0..grid[0].len() { 11 | if grid[j][i] == 1 { 12 | p += 4 - Solution::grid_num(&grid, (j as i32, i as i32)); 13 | } 14 | } 15 | } 16 | p 17 | } 18 | 19 | fn grid_num(grid: &Vec>, pos: (i32, i32)) -> i32 { 20 | const dxy: [(i32, i32); 4] = [(0 ,1), (0, -1), (-1, 0), (1, 0)]; 21 | let (m, n) = (grid.len(), grid[0].len()); 22 | let mut cnt: i32 = 0; 23 | for &d in &Solution::dxy { 24 | let next_pos:(i32, i32) = (pos.0 + d.0, pos.1 + d.1); 25 | if next_pos.0 >= 0 && next_pos.0 < m as i32 && 26 | next_pos.1 >= 0 && next_pos.1 < n as i32 && 27 | grid[next_pos.0 as usize][next_pos.1 as usize] == 1 { 28 | cnt += 1; 29 | } 30 | } 31 | cnt 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /n0494. Target Sum/README.md: -------------------------------------------------------------------------------- 1 | # Target Sum :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/target-sum](https://leetcode-cn.com/problems/target-sum) 3 | - 执行时间: 104 ms 4 | - 内存消耗: 2.8 MB 5 | - 通过日期: 2019-04-11 19:26 6 | 7 | ## 题目内容 8 |

给定一个非负整数数组,a1, a2, ..., an, 和一个目标数,S。现在你有两个符号 + 和 -。对于数组中的任意一个整数,你都可以从 + 或 -中选择一个符号添加在前面。

9 | 10 |

返回可以使最终数组和为目标数 S 的所有添加符号的方法数。

11 | 12 |

示例 1:

13 | 14 |
15 | 输入: nums: [1, 1, 1, 1, 1], S: 3
16 | 输出: 5
17 | 解释: 
18 | 
19 | -1+1+1+1+1 = 3
20 | +1-1+1+1+1 = 3
21 | +1+1-1+1+1 = 3
22 | +1+1+1-1+1 = 3
23 | +1+1+1+1-1 = 3
24 | 
25 | 一共有5种方法让最终目标和为3。
26 | 
27 | 28 |

注意:

29 | 30 |
    31 |
  1. 数组的长度不会超过20,并且数组中的值全为正数。
  2. 32 |
  3. 初始的数组的和不会超过1000。
  4. 33 |
  5. 保证返回的最终结果为32位整数。
  6. 34 |
35 | 36 | 37 | ## 解法 38 | ```rust 39 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 40 | // Zhihu: https://www.zhihu.com/people/netcan 41 | 42 | use std::collections::HashMap; 43 | impl Solution { 44 | pub fn find_target_sum_ways(nums: Vec, s: i32) -> i32 { 45 | let mut memo: HashMap<(i32, i32), i32> = HashMap::new(); // 记忆化 46 | Solution::target_sum_ways(&nums, s, -1, &mut memo) 47 | } 48 | 49 | fn target_sum_ways(nums: &Vec, s: i32, i: i32, memo: &mut HashMap<(i32, i32), i32>) -> i32 { 50 | if i >= nums.len() as i32 - 1 { 51 | if s == 0 { return 1; } 52 | else { return 0 }; 53 | } 54 | if memo.contains_key(&(i, s)) { return memo[&(i, s)]; } 55 | 56 | let ways = Solution::target_sum_ways(nums, s - nums[(i + 1) as usize], i + 1, memo) + // + 57 | Solution::target_sum_ways(nums, s + nums[(i + 1) as usize], i + 1, memo); // - 58 | 59 | memo.insert((i, s), ways); 60 | ways 61 | } 62 | 63 | } 64 | 65 | 66 | ``` -------------------------------------------------------------------------------- /n0494. Target Sum/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::HashMap; 5 | impl Solution { 6 | pub fn find_target_sum_ways(nums: Vec, s: i32) -> i32 { 7 | let mut memo: HashMap<(i32, i32), i32> = HashMap::new(); // 记忆化 8 | Solution::target_sum_ways(&nums, s, -1, &mut memo) 9 | } 10 | 11 | fn target_sum_ways(nums: &Vec, s: i32, i: i32, memo: &mut HashMap<(i32, i32), i32>) -> i32 { 12 | if i >= nums.len() as i32 - 1 { 13 | if s == 0 { return 1; } 14 | else { return 0 }; 15 | } 16 | if memo.contains_key(&(i, s)) { return memo[&(i, s)]; } 17 | 18 | let ways = Solution::target_sum_ways(nums, s - nums[(i + 1) as usize], i + 1, memo) + // + 19 | Solution::target_sum_ways(nums, s + nums[(i + 1) as usize], i + 1, memo); // - 20 | 21 | memo.insert((i, s), ways); 22 | ways 23 | } 24 | 25 | } 26 | 27 | -------------------------------------------------------------------------------- /n0514. Freedom Trail/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn find_rotate_steps(ring: String, key: String) -> i32 { 6 | let ring = ring.into_bytes(); 7 | let key = key.into_bytes(); 8 | // 记录各个字母的位置,快速检索用 9 | let mut alpha_pos = vec![Vec::new(); 26]; 10 | for (idx, &alpha) in ring.iter().enumerate() { 11 | alpha_pos[(alpha - 'a' as u8) as usize].push(idx); 12 | } 13 | 14 | // dp[k_idx][ring_pos] = min(dp[k_idx - 1][ring_pos] + step), step是上一步到这一步的距离 15 | let mut dp: Vec> = 16 | vec![vec![(ring.len() * key.len()) as i32; ring.len() + 1]; key.len() + 1]; 17 | 18 | dp[0][0] = 0; // 初始状态,转盘指向0点(ring_pos == 0) 19 | let ring_len = ring.len() as i32; 20 | 21 | for k_idx in 0..key.len() { 22 | for &k_pos in &alpha_pos[(key[k_idx] - 'a' as u8) as usize] { 23 | for ring_pos in 0..ring.len() { 24 | let step = ((k_pos as i32 - ring_pos as i32 + ring_len) % ring_len).min( 25 | (ring_pos as i32 - k_pos as i32 + ring_len) % ring_len 26 | ); 27 | 28 | dp[k_idx + 1][k_pos] = dp[k_idx + 1][k_pos].min( 29 | dp[k_idx][ring_pos] + step 30 | ); 31 | } 32 | } 33 | } 34 | 35 | dp[key.len()].iter().min().unwrap() + key.len() as i32 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /n0518. Coin Change 2/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter::repeat; 5 | impl Solution { 6 | pub fn change(amount: i32, coins: Vec) -> i32 { 7 | // dp[i][m]: 前i种硬币凑成m的个数 8 | // dp[i][m] = dp[i][m-coins[i]] + dp[i-1][m] 9 | // dp[i][0] = 1, dp[0][m] = 0 10 | 11 | let mut dp: Vec> = 12 | repeat(vec![0; amount as usize + 1]).take(coins.len() + 1).collect(); 13 | for i in 0..=coins.len() { dp[i][0] = 1; } 14 | 15 | for i in 0..coins.len() { 16 | for m in 1..=amount { 17 | dp[i + 1][m as usize] = if m >= coins[i] { 18 | dp[i + 1][(m - coins[i]) as usize] 19 | } else { 20 | 0 21 | } + dp[i][m as usize]; 22 | } 23 | } 24 | dp[coins.len()][amount as usize] 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /n0539. Minimum Time Difference/README.md: -------------------------------------------------------------------------------- 1 | # Minimum Time Difference :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/minimum-time-difference](https://leetcode-cn.com/problems/minimum-time-difference) 3 | - 执行时间: 4 ms 4 | - 内存消耗: 3.4 MB 5 | - 通过日期: 2019-03-07 18:50 6 | 7 | ## 题目内容 8 |

给定一个 24 小时制(小时:分钟)的时间列表,找出列表中任意两个时间的最小时间差并已分钟数表示。

9 | 10 |


11 | 示例 1:

12 | 13 |
14 | 输入: ["23:59","00:00"]
15 | 输出: 1
16 | 
17 | 18 |


19 | 备注:

20 | 21 |
    22 |
  1. 列表中时间数在 2~20000 之间。
  2. 23 |
  3. 每个时间取值在 00:00~23:59 之间。
  4. 24 |
25 | 26 | 27 | ## 解法 28 | ```rust 29 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 30 | // Zhihu: https://www.zhihu.com/people/netcan 31 | 32 | use std::cmp::min; 33 | impl Solution { 34 | pub fn find_min_difference(time_points: Vec) -> i32 { 35 | const FULL: i32 = 24 * 60; 36 | let mut sec:Vec = time_points.iter().map(|time| { 37 | time.split(":").map(|t| { 38 | t.parse::().unwrap() 39 | }).fold(0, |a, b| { a * 60 + b }) 40 | }).collect::>(); 41 | 42 | sec.sort(); 43 | sec.push(sec[0]); 44 | 45 | match sec.iter().scan(-1, |a, &b| { 46 | let ret = if *a == -1 { FULL } else { 47 | min((b - *a + FULL) % FULL, (*a - b + FULL) % FULL) 48 | }; 49 | *a = b; 50 | Some(ret) 51 | }).min() { 52 | Some(ans) => ans, 53 | None => 0 54 | } 55 | } 56 | } 57 | 58 | 59 | ``` -------------------------------------------------------------------------------- /n0539. Minimum Time Difference/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::min; 5 | impl Solution { 6 | pub fn find_min_difference(time_points: Vec) -> i32 { 7 | const FULL: i32 = 24 * 60; 8 | let mut sec:Vec = time_points.iter().map(|time| { 9 | time.split(":").map(|t| { 10 | t.parse::().unwrap() 11 | }).fold(0, |a, b| { a * 60 + b }) 12 | }).collect::>(); 13 | 14 | sec.sort(); 15 | sec.push(sec[0]); 16 | 17 | match sec.iter().scan(-1, |a, &b| { 18 | let ret = if *a == -1 { FULL } else { 19 | min((b - *a + FULL) % FULL, (*a - b + FULL) % FULL) 20 | }; 21 | *a = b; 22 | Some(ret) 23 | }).min() { 24 | Some(ans) => ans, 25 | None => 0 26 | } 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /n0563. Binary Tree Tilt/README.md: -------------------------------------------------------------------------------- 1 | # Binary Tree Tilt :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/binary-tree-tilt](https://leetcode-cn.com/problems/binary-tree-tilt) 3 | - 执行时间: 4 ms 4 | - 内存消耗: 3.2 MB 5 | - 通过日期: 2019-03-11 11:54 6 | 7 | ## 题目内容 8 |

给定一个二叉树,计算整个树的坡度。

9 | 10 |

一个树的节点的坡度定义即为,该节点左子树的结点之和和右子树结点之和的差的绝对值。空结点的的坡度是0。

11 | 12 |

整个树的坡度就是其所有节点的坡度之和。

13 | 14 |

示例:

15 | 16 |
17 | 输入: 
18 |          1
19 |        /   \
20 |       2     3
21 | 输出: 1
22 | 解释: 
23 | 结点的坡度 2 : 0
24 | 结点的坡度 3 : 0
25 | 结点的坡度 1 : |2-3| = 1
26 | 树的坡度 : 0 + 0 + 1 = 1
27 | 
28 | 29 |

注意:

30 | 31 |
    32 |
  1. 任何子树的结点的和不会超过32位整数的范围。
  2. 33 |
  3. 坡度的值不会超过32位整数的范围。
  4. 34 |
35 | 36 | 37 | ## 解法 38 | ```rust 39 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 40 | // Zhihu: https://www.zhihu.com/people/netcan 41 | 42 | use std::rc::Rc; 43 | use std::cell::RefCell; 44 | impl Solution { 45 | pub fn find_tilt(root: Option>>) -> i32 { 46 | let mut tilt = 0; 47 | Solution::cal_tilt_(&root, &mut tilt); 48 | tilt 49 | } 50 | fn cal_tilt_(root: &Option>>, tilt: &mut i32) -> i32 { 51 | match root { 52 | Some(node) => { 53 | let node = node.borrow(); 54 | 55 | let lsum = Solution::cal_tilt_(&node.left, tilt); 56 | let rsum = Solution::cal_tilt_(&node.right, tilt); 57 | *tilt += (lsum - rsum).abs(); 58 | lsum + rsum + node.val 59 | }, 60 | None => 0 61 | } 62 | 63 | } 64 | } 65 | 66 | 67 | ``` -------------------------------------------------------------------------------- /n0563. Binary Tree Tilt/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn find_tilt(root: Option>>) -> i32 { 8 | let mut tilt = 0; 9 | Solution::cal_tilt_(&root, &mut tilt); 10 | tilt 11 | } 12 | fn cal_tilt_(root: &Option>>, tilt: &mut i32) -> i32 { 13 | match root { 14 | Some(node) => { 15 | let node = node.borrow(); 16 | 17 | let lsum = Solution::cal_tilt_(&node.left, tilt); 18 | let rsum = Solution::cal_tilt_(&node.right, tilt); 19 | *tilt += (lsum - rsum).abs(); 20 | lsum + rsum + node.val 21 | }, 22 | None => 0 23 | } 24 | 25 | } 26 | } 27 | 28 | -------------------------------------------------------------------------------- /n0583. Delete Operation for Two Strings/README.md: -------------------------------------------------------------------------------- 1 | # Delete Operation for Two Strings :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/delete-operation-for-two-strings](https://leetcode-cn.com/problems/delete-operation-for-two-strings) 3 | - 执行时间: 12 ms 4 | - 内存消耗: 3.7 MB 5 | - 通过日期: 2019-03-20 15:45 6 | 7 | ## 题目内容 8 |

给定两个单词 word1 和 word2,找到使得 word1 和 word2 相同所需的最小步数,每步可以删除任意一个字符串中的一个字符。

9 | 10 |

示例 1:

11 | 12 |
13 | 输入: "sea", "eat"
14 | 输出: 2
15 | 解释: 第一步将"sea"变为"ea",第二步将"eat"变为"ea"
16 | 
17 | 18 |

说明:

19 | 20 |
    21 |
  1. 给定单词的长度不超过500。
  2. 22 |
  3. 给定单词中的字符只含有小写字母。
  4. 23 |
24 | 25 | 26 | ## 解法 27 | ```rust 28 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 29 | // Zhihu: https://www.zhihu.com/people/netcan 30 | 31 | use std::iter; 32 | impl Solution { 33 | pub fn min_distance(word1: String, word2: String) -> i32 { 34 | // 转换成LCS问题 35 | let (m, n) = (word1.len() as i32, word2.len() as i32); 36 | let (word1, word2) = (word1.into_bytes(), word2.into_bytes()); 37 | let mut dp:Vec> = iter::repeat(vec![0; word2.len() + 1]).take(word1.len() + 1).collect(); 38 | for (i, &c1) in word1.iter().enumerate() { 39 | for (j, &c2) in word2.iter().enumerate() { 40 | dp[i + 1][j + 1] = 41 | if c1 == c2 { dp[i][j] + 1 } 42 | else { dp[i][j + 1].max(dp[i+1][j]) } 43 | } 44 | } 45 | 46 | m + n - 2 * dp[m as usize][n as usize] 47 | } 48 | } 49 | 50 | 51 | ``` -------------------------------------------------------------------------------- /n0583. Delete Operation for Two Strings/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | impl Solution { 6 | pub fn min_distance(word1: String, word2: String) -> i32 { 7 | // 转换成LCS问题 8 | let (m, n) = (word1.len() as i32, word2.len() as i32); 9 | let (word1, word2) = (word1.into_bytes(), word2.into_bytes()); 10 | let mut dp:Vec> = iter::repeat(vec![0; word2.len() + 1]).take(word1.len() + 1).collect(); 11 | for (i, &c1) in word1.iter().enumerate() { 12 | for (j, &c2) in word2.iter().enumerate() { 13 | dp[i + 1][j + 1] = 14 | if c1 == c2 { dp[i][j] + 1 } 15 | else { dp[i][j + 1].max(dp[i+1][j]) } 16 | } 17 | } 18 | 19 | m + n - 2 * dp[m as usize][n as usize] 20 | } 21 | } 22 | 23 | -------------------------------------------------------------------------------- /n0606. Construct String from Binary Tree/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn tree2str(t: Option>>) -> String { 8 | fn tree2str_(tree: &Option>>) -> String { 9 | match tree { 10 | None => format!(""), 11 | Some(root) => { 12 | let node = root.borrow(); 13 | let (left_str, right_str) = 14 | (tree2str_(&node.left), tree2str_(&node.right)); 15 | if right_str.len() > 0 { format!("{}({})({})", node.val, left_str, right_str) } 16 | else if left_str.len() > 0{ format!("{}({})", node.val, left_str) } 17 | else { format!("{}", node.val) } 18 | } 19 | } 20 | } 21 | tree2str_(&t) 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /n0630. Course Schedule III/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::{min, max}; 5 | use std::iter; 6 | impl Solution { 7 | pub fn schedule_course(mut courses: Vec>) -> i32 { 8 | courses.sort_by(|a, b| { a[1].cmp(&b[1]) }); 9 | let max_d = min(courses.last().unwrap()[1], courses.iter().fold(0, |sum_d, c| { 10 | sum_d + c[0] 11 | })); 12 | 13 | // dp[t]: 第t天最多完成的科目数 14 | let mut dp = vec![0; max_d as usize + 1]; 15 | let mut ans: i32 = 0; 16 | 17 | for (idx, c) in courses.iter().enumerate() { 18 | for t in (c[0] as usize ..= max_d as usize).rev() { 19 | if t <= (c[1] as usize) { // 可学 20 | dp[t] = max(dp[t], dp[t - c[0] as usize] + 1); 21 | ans = max(ans, dp[t]); 22 | } 23 | } 24 | } 25 | 26 | ans 27 | } 28 | } 29 | 30 | #[cfg(test)] 31 | mod tests { 32 | use super::*; 33 | #[test] 34 | fn test_1() { 35 | assert_eq!(Solution::schedule_course( 36 | vec![vec![100, 200], 37 | vec![200, 1300], 38 | vec![1000, 1250], 39 | vec![2000, 3200]] 40 | ), 3); 41 | } 42 | #[test] 43 | fn test_2() { 44 | assert_eq!(Solution::schedule_course( 45 | vec![vec![2,5],vec![2,19],vec![1,8],vec![1,3]] 46 | ), 4); 47 | } 48 | } 49 | 50 | -------------------------------------------------------------------------------- /n0661. Image Smoother/README.md: -------------------------------------------------------------------------------- 1 | # Image Smoother :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/image-smoother](https://leetcode-cn.com/problems/image-smoother) 3 | - 执行时间: 28 ms 4 | - 内存消耗: 3 MB 5 | - 通过日期: 2019-03-25 20:46 6 | 7 | ## 题目内容 8 |

包含整数的二维矩阵 M 表示一个图片的灰度。你需要设计一个平滑器来让每一个单元的灰度成为平均灰度 (向下舍入) ,平均灰度的计算是周围的8个单元和它本身的值求平均,如果周围的单元格不足八个,则尽可能多的利用它们。

9 | 10 |

示例 1:

11 | 12 |
13 | 输入:
14 | [[1,1,1],
15 |  [1,0,1],
16 |  [1,1,1]]
17 | 输出:
18 | [[0, 0, 0],
19 |  [0, 0, 0],
20 |  [0, 0, 0]]
21 | 解释:
22 | 对于点 (0,0), (0,2), (2,0), (2,2): 平均(3/4) = 平均(0.75) = 0
23 | 对于点 (0,1), (1,0), (1,2), (2,1): 平均(5/6) = 平均(0.83333333) = 0
24 | 对于点 (1,1): 平均(8/9) = 平均(0.88888889) = 0
25 | 
26 | 27 |

注意:

28 | 29 |
    30 |
  1. 给定矩阵中的整数范围为 [0, 255]。
  2. 31 |
  3. 矩阵的长和宽的范围均为 [1, 150]。
  4. 32 |
33 | 34 | 35 | ## 解法 36 | ```rust 37 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 38 | // Zhihu: https://www.zhihu.com/people/netcan 39 | 40 | impl Solution { 41 | const dx: [i32; 9] = [0, 1, 0, -1, 1, 1, -1, -1, 0]; 42 | const dy: [i32; 9] = [-1, 0, 1, 0, -1, 1, 1, -1, 0]; 43 | pub fn image_smoother(m: Vec>) -> Vec> { 44 | let mut res = m.clone(); 45 | for i in 0..m.len() { 46 | for j in 0..m[0].len() { 47 | let (mut l, mut sum) = (0, 0); 48 | for k in 0..9 { 49 | let (x, y) = (i as i32 + Solution::dx[k], 50 | j as i32 + Solution::dy[k]); 51 | if x >= 0 && x < m.len() as i32 && 52 | y >= 0 && y < m[0].len() as i32 { 53 | sum += m[x as usize][y as usize]; 54 | l += 1; 55 | } 56 | } 57 | res[i][j] = sum / l; 58 | } 59 | } 60 | res 61 | } 62 | } 63 | 64 | ``` -------------------------------------------------------------------------------- /n0661. Image Smoother/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | const dx: [i32; 9] = [0, 1, 0, -1, 1, 1, -1, -1, 0]; 6 | const dy: [i32; 9] = [-1, 0, 1, 0, -1, 1, 1, -1, 0]; 7 | pub fn image_smoother(m: Vec>) -> Vec> { 8 | let mut res = m.clone(); 9 | for i in 0..m.len() { 10 | for j in 0..m[0].len() { 11 | let (mut l, mut sum) = (0, 0); 12 | for k in 0..9 { 13 | let (x, y) = (i as i32 + Solution::dx[k], 14 | j as i32 + Solution::dy[k]); 15 | if x >= 0 && x < m.len() as i32 && 16 | y >= 0 && y < m[0].len() as i32 { 17 | sum += m[x as usize][y as usize]; 18 | l += 1; 19 | } 20 | } 21 | res[i][j] = sum / l; 22 | } 23 | } 24 | res 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /n0671. Second Minimum Node In a Binary Tree/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | use std::cmp; 7 | impl Solution { 8 | pub fn find_second_minimum_value(root: Option>>) -> i32 { 9 | match &root { 10 | Some(node) => Solution::find_second_minimum_value_(&root, node.borrow().val), 11 | None => -1 12 | } 13 | } 14 | 15 | fn find_second_minimum_value_(root: &Option>>, val: i32) -> i32 { 16 | match root { 17 | Some(node) => { 18 | let node = node.borrow(); 19 | if node.val > val { 20 | return node.val; 21 | } 22 | let l = Solution::find_second_minimum_value_(&node.left, val); 23 | let r = Solution::find_second_minimum_value_(&node.right, val); 24 | if l < 0 { 25 | return r; 26 | } 27 | if r < 0 { 28 | return l; 29 | } 30 | cmp::min(l, r) 31 | }, 32 | None => { 33 | -1 34 | } 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /n0673. Number of Longest Increasing Subsequence/README.md: -------------------------------------------------------------------------------- 1 | # Number of Longest Increasing Subsequence :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence](https://leetcode-cn.com/problems/number-of-longest-increasing-subsequence) 3 | - 执行时间: 24 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-21 12:17 6 | 7 | ## 题目内容 8 |

给定一个未排序的整数数组,找到最长递增子序列的个数。

9 | 10 |

示例 1:

11 | 12 |
13 | 输入: [1,3,5,4,7]
14 | 输出: 2
15 | 解释: 有两个最长递增子序列,分别是 [1, 3, 4, 7] 和[1, 3, 5, 7]。
16 | 
17 | 18 |

示例 2:

19 | 20 |
21 | 输入: [2,2,2,2,2]
22 | 输出: 5
23 | 解释: 最长递增子序列的长度是1,并且存在5个子序列的长度为1,因此输出5。
24 | 
25 | 26 |

注意: 给定的数组长度不超过 2000 并且结果一定是32位有符号整数。

27 | 28 | 29 | ## 解法 30 | ```rust 31 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 32 | // Zhihu: https://www.zhihu.com/people/netcan 33 | 34 | impl Solution { 35 | pub fn find_number_of_lis(nums: Vec) -> i32 { 36 | if nums.len() <= 1 { return nums.len() as i32; } 37 | let mut dp = vec![1; nums.len()]; // dp[i]以nums[i]结尾的LIS 38 | let mut dp_len = vec![1; nums.len()]; 39 | let (mut max_len, mut cnt) = (1, 0); 40 | for i in 0..nums.len() { 41 | for j in i+1..nums.len() { 42 | if nums[j] > nums[i] { 43 | if dp[i] + 1 > dp[j] { 44 | dp[j] = dp[i] + 1; 45 | dp_len[j] = dp_len[i]; 46 | } else if dp[i]+ 1 == dp[j] { 47 | dp_len[j] += dp_len[i]; 48 | } 49 | max_len = max_len.max(dp[j]); 50 | } 51 | } 52 | } 53 | let mut cnt = 0; 54 | for (i, &len) in dp.iter().enumerate() { 55 | if len == max_len { cnt += dp_len[i]; } 56 | } 57 | cnt 58 | } 59 | } 60 | 61 | 62 | ``` -------------------------------------------------------------------------------- /n0673. Number of Longest Increasing Subsequence/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn find_number_of_lis(nums: Vec) -> i32 { 6 | if nums.len() <= 1 { return nums.len() as i32; } 7 | let mut dp = vec![1; nums.len()]; // dp[i]以nums[i]结尾的LIS 8 | let mut dp_len = vec![1; nums.len()]; 9 | let (mut max_len, mut cnt) = (1, 0); 10 | for i in 0..nums.len() { 11 | for j in i+1..nums.len() { 12 | if nums[j] > nums[i] { 13 | if dp[i] + 1 > dp[j] { 14 | dp[j] = dp[i] + 1; 15 | dp_len[j] = dp_len[i]; 16 | } else if dp[i]+ 1 == dp[j] { 17 | dp_len[j] += dp_len[i]; 18 | } 19 | max_len = max_len.max(dp[j]); 20 | } 21 | } 22 | } 23 | let mut cnt = 0; 24 | for (i, &len) in dp.iter().enumerate() { 25 | if len == max_len { cnt += dp_len[i]; } 26 | } 27 | cnt 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /n0674. Longest Continuous Increasing Subsequence/README.md: -------------------------------------------------------------------------------- 1 | # Longest Continuous Increasing Subsequence :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence](https://leetcode-cn.com/problems/longest-continuous-increasing-subsequence) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.7 MB 5 | - 通过日期: 2019-03-15 12:09 6 | 7 | ## 题目内容 8 |

给定一个未经排序的整数数组,找到最长且连续的的递增序列。

9 | 10 |

示例 1:

11 | 12 |
13 | 输入: [1,3,5,4,7]
14 | 输出: 3
15 | 解释: 最长连续递增序列是 [1,3,5], 长度为3。
16 | 尽管 [1,3,5,7] 也是升序的子序列, 但它不是连续的,因为5和7在原数组里被4隔开。 
17 | 
18 | 19 |

示例 2:

20 | 21 |
22 | 输入: [2,2,2,2,2]
23 | 输出: 1
24 | 解释: 最长连续递增序列是 [2], 长度为1。
25 | 
26 | 27 |

注意:数组长度不会超过10000。

28 | 29 | 30 | ## 解法 31 | ```rust 32 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 33 | // Zhihu: https://www.zhihu.com/people/netcan 34 | 35 | use std::cmp::max; 36 | impl Solution { 37 | pub fn find_length_of_lcis(nums: Vec) -> i32 { 38 | if nums.len() == 0 { return 0; } 39 | let (mut length, mut max_length) = (1, 1); 40 | nums.iter().skip(1).fold(nums[0], |a, b| { 41 | if a < *b { length += 1; max_length = max(max_length, length) } 42 | else { length = 1; } 43 | *b 44 | }); 45 | max_length 46 | } 47 | } 48 | 49 | 50 | ``` -------------------------------------------------------------------------------- /n0674. Longest Continuous Increasing Subsequence/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::max; 5 | impl Solution { 6 | pub fn find_length_of_lcis(nums: Vec) -> i32 { 7 | if nums.len() == 0 { return 0; } 8 | let (mut length, mut max_length) = (1, 1); 9 | nums.iter().skip(1).fold(nums[0], |a, b| { 10 | if a < *b { length += 1; max_length = max(max_length, length) } 11 | else { length = 1; } 12 | *b 13 | }); 14 | max_length 15 | } 16 | } 17 | 18 | -------------------------------------------------------------------------------- /n0679. 24 Game/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn judge_point24(nums: Vec) -> bool { 6 | Solution::judge_point24_( 7 | nums.iter().map(|&x| { x as f64 }).collect() 8 | ) 9 | } 10 | 11 | pub fn judge_point24_(nums: Vec) -> bool { 12 | if nums.len() == 0 { return false; } 13 | if nums.len() == 1 && (nums[0] - 24.0).abs() < 1e-6 { return true; } 14 | // 选出2个数,进行运算,然后放回列表中 15 | for i in 0..nums.len() { 16 | for j in 0..nums.len() { 17 | if i == j { 18 | continue; 19 | } 20 | for op in &['+', '*', '-', '/'] { 21 | let mut nums_: Vec = nums.iter() 22 | .enumerate() 23 | .filter(|&(k, _)| k != i && k != j) 24 | .map(|(_, v)| v ) 25 | .cloned().collect(); 26 | match op { 27 | '+' => if (i < j) { nums_.push(nums[i] + nums[j]) } else { continue; }, 28 | '*' => if (i < j) { nums_.push(nums[i] * nums[j]) } else { continue; }, 29 | '-' => nums_.push(nums[i] - nums[j]), 30 | '/' => nums_.push(nums[i] / nums[j]), 31 | _ => {} 32 | }; 33 | if Solution::judge_point24_(nums_) { return true; } 34 | } 35 | } 36 | } 37 | 38 | false 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /n0687. Longest Univalue Path/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | use std::cmp::max; 7 | impl Solution { 8 | pub fn longest_univalue_path(root: Option>>) -> i32 { 9 | let mut max_length = 0; 10 | Solution::longest_univalue_path_(&root, &mut max_length); 11 | max_length 12 | } 13 | 14 | fn longest_univalue_path_(root: &Option>>, max_length: &mut i32) -> i32 { 15 | match root { 16 | Some(node) => { 17 | let node = node.borrow(); 18 | let l = Solution::longest_univalue_path_(&node.left, max_length); 19 | let r = Solution::longest_univalue_path_(&node.right, max_length); 20 | let (mut l_len, mut r_len) = (0, 0); 21 | if let Some(ref left) = node.left { 22 | if left.borrow().val == node.val { 23 | l_len = l + 1; 24 | } 25 | } 26 | if let Some(ref right) = node.right { 27 | if right.borrow().val == node.val { 28 | r_len = r + 1; 29 | } 30 | } 31 | *max_length = max(*max_length, l_len + r_len); 32 | max(l_len, r_len) 33 | }, 34 | None => { 35 | 0 36 | } 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /n0691. Stickers to Spell Word/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::VecDeque; 5 | use std::collections::HashMap; 6 | impl Solution { 7 | pub fn min_stickers(stickers: Vec, target: String) -> i32 { 8 | // stickers[i] = Map(char, char_count) 9 | let stickers: Vec> = stickers.into_iter().map(|x| { 10 | let mut char_count = HashMap::new(); 11 | for c in x.into_bytes() { 12 | *char_count.entry(c).or_insert(0) += 1; 13 | } 14 | char_count 15 | }).collect(); 16 | let target = target.into_bytes(); 17 | let mut vis = vec![false; 1 << target.len()]; 18 | let mut que = VecDeque::new(); 19 | // que: (i16: 每一位代表是否完成字母, step) 20 | // 0101:表示第1, 3个字母已经填上 21 | que.push_back((0u16, 0)); 22 | vis[0] = true; 23 | 24 | // BFS 25 | while !que.is_empty() { 26 | let (cur_chars, cur_step) = que.pop_front().unwrap(); 27 | if cur_chars == (1 << target.len()) - 1 { 28 | return cur_step; 29 | } 30 | 31 | for sticker in &stickers { 32 | let mut next_chars = cur_chars; 33 | let mut char_count = sticker.clone(); 34 | for i in (0..target.len()) { 35 | if next_chars & (1 << i) == 0 && *char_count.entry(target[i]).or_insert(0) > 0 { 36 | *char_count.get_mut(&target[i]).unwrap() -= 1; 37 | next_chars |= (1 << i); 38 | } 39 | } 40 | 41 | if next_chars != cur_chars && !vis[next_chars as usize] { 42 | que.push_back((next_chars, cur_step + 1)); 43 | vis[next_chars as usize] = true; 44 | } 45 | } 46 | 47 | } 48 | 49 | -1 50 | } 51 | } 52 | 53 | -------------------------------------------------------------------------------- /n0695. Max Area of Island/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::VecDeque; 5 | use std::cmp::max; 6 | impl Solution { 7 | const dxy: [(i32, i32); 4] = [(0 ,1), (0, -1), (-1, 0), (1, 0)]; 8 | pub fn max_area_of_island(mut grid: Vec>) -> i32 { 9 | let mut max_area: i32 = 0; 10 | for j in (0..grid.len()) { 11 | for i in (0..grid[0].len()) { 12 | if grid[j][i] == 1 { 13 | max_area = max(max_area, Solution::island_area(&mut grid, (j as i32, i as i32))); 14 | } 15 | } 16 | } 17 | max_area 18 | } 19 | fn island_area(grid: &mut Vec>, pos: (i32, i32)) -> i32 { 20 | if grid[pos.0 as usize][pos.1 as usize] == 0 { 21 | 0 22 | } else { 23 | let mut area = 0; 24 | let mut que = VecDeque::new(); 25 | let (m, n) = (grid.len(), grid[0].len()); 26 | grid[pos.0 as usize][pos.1 as usize] = 0; 27 | que.push_back(pos); 28 | while !que.is_empty() { 29 | let last_pos = que.pop_front().unwrap(); 30 | area += 1; 31 | for &d in &Solution::dxy { 32 | let next_pos:(i32, i32) = (last_pos.0 + d.0, last_pos.1 + d.1); 33 | if next_pos.0 >= 0 && next_pos.0 < m as i32 && 34 | next_pos.1 >= 0 && next_pos.1 < n as i32 && 35 | grid[next_pos.0 as usize][next_pos.1 as usize] == 1 { 36 | grid[next_pos.0 as usize][next_pos.1 as usize] = 0; 37 | que.push_back(next_pos); 38 | } 39 | } 40 | } 41 | 42 | area 43 | } 44 | } 45 | 46 | } 47 | 48 | -------------------------------------------------------------------------------- /n0699. Falling Squares/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | struct Box { 5 | l: i32, 6 | r: i32, 7 | h: i32, 8 | } 9 | 10 | impl Solution { 11 | pub fn falling_squares(mut positions: Vec>) -> Vec { 12 | let mut max_height = 0; 13 | let mut height = vec![]; 14 | let mut boxes: Vec = vec![]; 15 | for p in &positions { 16 | let (cl, cr) = (p[0], p[0] + p[1]); 17 | let mut maxh = p[1]; 18 | for b in &boxes { 19 | // 计算重叠部分 20 | if cr > b.l && cl < b.r { maxh = maxh.max(b.h + p[1]); } 21 | } 22 | boxes.push(Box { 23 | l: cl, 24 | r: cr, 25 | h: maxh // 更新最大值 26 | }); 27 | max_height = max_height.max(maxh); 28 | height.push(max_height); 29 | } 30 | height 31 | } 32 | } 33 | 34 | -------------------------------------------------------------------------------- /n0728. Self Dividing Numbers/README.md: -------------------------------------------------------------------------------- 1 | # Self Dividing Numbers :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/self-dividing-numbers](https://leetcode-cn.com/problems/self-dividing-numbers) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-06 09:28 6 | 7 | ## 题目内容 8 |

自除数 是指可以被它包含的每一位数除尽的数。

9 | 10 |

例如,128 是一个自除数,因为 128 % 1 == 0128 % 2 == 0128 % 8 == 0

11 | 12 |

还有,自除数不允许包含 0 。

13 | 14 |

给定上边界和下边界数字,输出一个列表,列表的元素是边界(含边界)内所有的自除数。

15 | 16 |

示例 1:

17 | 18 |
19 | 输入: 
20 | 上边界left = 1, 下边界right = 22
21 | 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22]
22 | 
23 | 24 |

注意:

25 | 26 |
    27 |
  • 每个输入参数的边界满足 1 <= left <= right <= 10000
  • 28 |
29 | 30 | 31 | ## 解法 32 | ```rust 33 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 34 | // Zhihu: https://www.zhihu.com/people/netcan 35 | 36 | impl Solution { 37 | pub fn self_dividing_numbers(left: i32, right: i32) -> Vec { 38 | let ret = (left..=right).filter(|&x| { 39 | let mut _x = x; 40 | let mut dividing = true; 41 | while(_x > 0) { 42 | if(_x % 10 == 0 || (x % (_x % 10)) != 0) { 43 | dividing = false; 44 | break; 45 | } 46 | _x /= 10; 47 | } 48 | dividing 49 | }).collect(); 50 | ret 51 | } 52 | } 53 | 54 | 55 | ``` -------------------------------------------------------------------------------- /n0728. Self Dividing Numbers/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn self_dividing_numbers(left: i32, right: i32) -> Vec { 6 | let ret = (left..=right).filter(|&x| { 7 | let mut _x = x; 8 | let mut dividing = true; 9 | while(_x > 0) { 10 | if(_x % 10 == 0 || (x % (_x % 10)) != 0) { 11 | dividing = false; 12 | break; 13 | } 14 | _x /= 10; 15 | } 16 | dividing 17 | }).collect(); 18 | ret 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /n0740. Delete and Earn/README.md: -------------------------------------------------------------------------------- 1 | # Delete and Earn :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/delete-and-earn](https://leetcode-cn.com/problems/delete-and-earn) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-04-17 20:03 6 | 7 | ## 题目内容 8 |

给定一个整数数组 nums ,你可以对它进行一些操作。

9 | 10 |

每次操作中,选择任意一个 nums[i] ,删除它并获得 nums[i] 的点数。之后,你必须删除每个等于 nums[i] - 1 或 nums[i] + 1 的元素。

11 | 12 |

开始你拥有 0 个点数。返回你能通过这些操作获得的最大点数。

13 | 14 |

示例 1:

15 | 16 |
17 | 输入: nums = [3, 4, 2]
18 | 输出: 6
19 | 解释: 
20 | 删除 4 来获得 4 个点数,因此 3 也被删除。
21 | 之后,删除 2 来获得 2 个点数。总共获得 6 个点数。
22 | 
23 | 24 |

示例 2:

25 | 26 |
27 | 输入: nums = [2, 2, 3, 3, 3, 4]
28 | 输出: 9
29 | 解释: 
30 | 删除 3 来获得 3 个点数,接着要删除两个 2 和 4 。
31 | 之后,再次删除 3 获得 3 个点数,再次删除 3 获得 3 个点数。
32 | 总共获得 9 个点数。
33 | 
34 | 35 |

注意:

36 | 37 |
    38 |
  • nums的长度最大为20000
  • 39 |
  • 每个整数nums[i]的大小都在[1, 10000]范围内。
  • 40 |
41 | 42 | 43 | ## 解法 44 | ```rust 45 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 46 | // Zhihu: https://www.zhihu.com/people/netcan 47 | 48 | impl Solution { 49 | pub fn delete_and_earn(nums: Vec) -> i32 { 50 | // 打家劫舍问题 51 | let mut gold = [0; 10001]; 52 | for &n in &nums { 53 | gold[n as usize] += n; 54 | } 55 | let mut dp = [0; 10001]; 56 | let (mut take, mut max_earn) = (0, 0); 57 | for i in 1..=10000usize { 58 | dp[i] = if i > 1 { 59 | take = take.max(dp[i - 2]); // dp[0..=i-2].max() 60 | take + gold[i] 61 | } else { 62 | gold[i] 63 | }; 64 | max_earn = max_earn.max(dp[i]); 65 | } 66 | 67 | max_earn 68 | } 69 | } 70 | 71 | 72 | ``` -------------------------------------------------------------------------------- /n0740. Delete and Earn/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn delete_and_earn(nums: Vec) -> i32 { 6 | // 打家劫舍问题 7 | let mut gold = [0; 10001]; 8 | for &n in &nums { 9 | gold[n as usize] += n; 10 | } 11 | let mut dp = [0; 10001]; 12 | let (mut take, mut max_earn) = (0, 0); 13 | for i in 1..=10000usize { 14 | dp[i] = if i > 1 { 15 | take = take.max(dp[i - 2]); // dp[0..=i-2].max() 16 | take + gold[i] 17 | } else { 18 | gold[i] 19 | }; 20 | max_earn = max_earn.max(dp[i]); 21 | } 22 | 23 | max_earn 24 | } 25 | } 26 | 27 | -------------------------------------------------------------------------------- /n0744. Find Smallest Letter Greater Than Target/README.md: -------------------------------------------------------------------------------- 1 | # Find Smallest Letter Greater Than Target :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target](https://leetcode-cn.com/problems/find-smallest-letter-greater-than-target) 3 | - 执行时间: 8 ms 4 | - 内存消耗: 3.1 MB 5 | - 通过日期: 2019-03-05 18:58 6 | 7 | ## 题目内容 8 |

给定一个只包含小写字母的有序数组letters 和一个目标字母 target,寻找有序数组里面比目标字母大的最小字母。

9 | 10 |

数组里字母的顺序是循环的。举个例子,如果目标字母target = 'z' 并且有序数组为 letters = ['a', 'b'],则答案返回 'a'

11 | 12 |

示例:

13 | 14 |
15 | 输入:
16 | letters = ["c", "f", "j"]
17 | target = "a"
18 | 输出: "c"
19 | 
20 | 输入:
21 | letters = ["c", "f", "j"]
22 | target = "c"
23 | 输出: "f"
24 | 
25 | 输入:
26 | letters = ["c", "f", "j"]
27 | target = "d"
28 | 输出: "f"
29 | 
30 | 输入:
31 | letters = ["c", "f", "j"]
32 | target = "g"
33 | 输出: "j"
34 | 
35 | 输入:
36 | letters = ["c", "f", "j"]
37 | target = "j"
38 | 输出: "c"
39 | 
40 | 输入:
41 | letters = ["c", "f", "j"]
42 | target = "k"
43 | 输出: "c"
44 | 
45 | 46 |

注:

47 | 48 |
    49 |
  1. letters长度范围在[2, 10000]区间内。
  2. 50 |
  3. letters 仅由小写字母组成,最少包含两个不同的字母。
  4. 51 |
  5. 目标字母target 是一个小写字母。
  6. 52 |
53 | 54 | 55 | ## 解法 56 | ```rust 57 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 58 | // Zhihu: https://www.zhihu.com/people/netcan 59 | 60 | impl Solution { 61 | pub fn next_greatest_letter(letters: Vec, target: char) -> char { 62 | for c in letters.iter() { 63 | if *c > target { 64 | return *c; 65 | } 66 | } 67 | letters[0] 68 | } 69 | } 70 | 71 | 72 | ``` -------------------------------------------------------------------------------- /n0744. Find Smallest Letter Greater Than Target/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn next_greatest_letter(letters: Vec, target: char) -> char { 6 | for c in letters.iter() { 7 | if *c > target { 8 | return *c; 9 | } 10 | } 11 | letters[0] 12 | } 13 | } 14 | 15 | -------------------------------------------------------------------------------- /n0787. Cheapest Flights Within K Stops/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter::repeat; 5 | use std::collections::VecDeque; 6 | #[derive(Clone)] 7 | struct Edge { 8 | to: i32, 9 | cost: i32 10 | } 11 | impl Solution { 12 | pub fn find_cheapest_price(n: i32, flights: Vec>, src: i32, dst: i32, k: i32) -> i32 { 13 | let mut graph: Vec> = repeat(Vec::new()).take(n as usize).collect(); 14 | for e in &flights { 15 | graph[e[0] as usize].push(Edge { 16 | to: e[1], 17 | cost: e[2], 18 | }); 19 | } 20 | 21 | let mut vis = vec![false; n as usize]; 22 | vis[src as usize] = true; 23 | 24 | let mut min_cost = i32::max_value(); 25 | Solution::dfs(&graph, src, dst, 0, k, 0, &mut min_cost, &mut vis); 26 | if min_cost == i32::max_value() { -1 } 27 | else { min_cost } 28 | } 29 | fn dfs(graph: &Vec>, src: i32, dst: i32, cur_step: i32, k: i32, cost: i32, min_cost: &mut i32, vis: &mut Vec) { 30 | if cur_step >= k + 2 || cost > *min_cost { return; } 31 | if src == dst { *min_cost = (*min_cost).min(cost); return; } 32 | 33 | for e in &graph[src as usize] { 34 | if !vis[e.to as usize] { 35 | vis[e.to as usize] = true; 36 | Solution::dfs(graph, e.to, dst, cur_step + 1, k, cost + e.cost, min_cost, vis); 37 | vis[e.to as usize] = false; 38 | } 39 | } 40 | } 41 | 42 | } 43 | -------------------------------------------------------------------------------- /n0792. Number of Matching Subsequences/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::HashMap; 5 | impl Solution { 6 | pub fn num_matching_subseq(s: String, words: Vec) -> i32 { 7 | let s = s.into_bytes(); 8 | let words: Vec> = words.into_iter().map(|w| { w.into_bytes() }).collect(); 9 | 10 | // 预处理s 11 | let mut s_char_pos = HashMap::new(); 12 | for (pos, c) in s.iter().enumerate() { 13 | let c_pos_list = s_char_pos.entry(c).or_insert(Vec::new()); 14 | c_pos_list.push(pos); 15 | } 16 | 17 | let mut cnt = 0; 18 | for word in &words { 19 | let mut w_pos = 0; 20 | let mut is_seq = true; 21 | for w in word { 22 | if !s_char_pos.contains_key(&w) { 23 | is_seq = false; break; 24 | } 25 | let pos_list = s_char_pos.get(&w).unwrap(); 26 | match pos_list.binary_search(&w_pos) { 27 | Ok(idx) => { w_pos = pos_list[idx] + 1; }, 28 | Err(idx) => { 29 | if(idx >= 0 && idx < pos_list.len()) { w_pos = pos_list[idx] + 1; } 30 | else { is_seq = false; break; } 31 | } 32 | } 33 | } 34 | if is_seq { cnt += 1; } 35 | } 36 | 37 | cnt 38 | } 39 | } 40 | 41 | -------------------------------------------------------------------------------- /n0836. Rectangle Overlap/README.md: -------------------------------------------------------------------------------- 1 | # Rectangle Overlap :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/rectangle-overlap](https://leetcode-cn.com/problems/rectangle-overlap) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.3 MB 5 | - 通过日期: 2019-03-14 23:56 6 | 7 | ## 题目内容 8 |

矩形以列表 [x1, y1, x2, y2] 的形式表示,其中 (x1, y1) 为左下角的坐标,(x2, y2) 是右上角的坐标。

9 | 10 |

如果相交的面积为正,则称两矩形重叠。需要明确的是,只在角或边接触的两个矩形不构成重叠。

11 | 12 |

给出两个矩形,判断它们是否重叠并返回结果。

13 | 14 |

示例 1:

15 | 16 |
输入:rec1 = [0,0,2,2], rec2 = [1,1,3,3]
17 | 输出:true
18 | 
19 | 20 |

示例 2:

21 | 22 |
输入:rec1 = [0,0,1,1], rec2 = [1,0,2,1]
23 | 输出:false
24 | 
25 | 26 |

说明:

27 | 28 |
    29 |
  1. 两个矩形 rec1rec2 都以含有四个整数的列表的形式给出。
  2. 30 |
  3. 矩形中的所有坐标都处于 -10^910^9 之间。
  4. 31 |
32 | 33 | 34 | ## 解法 35 | ```rust 36 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 37 | // Zhihu: https://www.zhihu.com/people/netcan 38 | 39 | use std::cmp::{max, min}; 40 | impl Solution { 41 | pub fn is_rectangle_overlap(rec1: Vec, rec2: Vec) -> bool { 42 | let (a, b, c, d, e, f, g, h) = 43 | (rec1[0], rec1[1], rec1[2], rec1[3], rec2[0], rec2[1], rec2[2], rec2[3]); 44 | // 重叠部分 45 | min(h, d) - max(f, b) > 0 && min(c, g) - max(a, e) > 0 46 | } 47 | } 48 | 49 | ``` -------------------------------------------------------------------------------- /n0836. Rectangle Overlap/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::{max, min}; 5 | impl Solution { 6 | pub fn is_rectangle_overlap(rec1: Vec, rec2: Vec) -> bool { 7 | let (a, b, c, d, e, f, g, h) = 8 | (rec1[0], rec1[1], rec1[2], rec1[3], rec2[0], rec2[1], rec2[2], rec2[3]); 9 | // 重叠部分 10 | min(h, d) - max(f, b) > 0 && min(c, g) - max(a, e) > 0 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /n0851. Loud and Rich/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn loud_and_rich(richer: Vec>, quiet: Vec) -> Vec { 6 | let mut graph = vec![vec![]; quiet.len()]; // 邻接表 7 | let mut ans = vec![-1; quiet.len()]; 8 | for e in &richer { 9 | graph[e[1] as usize].push(e[0]); 10 | } 11 | for v in 0..quiet.len() { 12 | ans[v] = Solution::find_min_quiet(v, &mut ans, &graph, &quiet) as i32; 13 | } 14 | 15 | ans 16 | } 17 | fn find_min_quiet(p: usize, memo: &mut Vec, graph: &Vec>, quiet: &Vec) -> usize { 18 | if memo[p] != -1 { return memo[p] as usize; } 19 | 20 | let mut min_quiet = p; 21 | for &v in &graph[p] { 22 | let q = Solution::find_min_quiet(v as usize, memo, graph, quiet); 23 | if quiet[min_quiet] > quiet[q] { min_quiet = q; } 24 | } 25 | 26 | memo[p] = min_quiet as i32; 27 | min_quiet 28 | } 29 | } 30 | 31 | -------------------------------------------------------------------------------- /n0856. Score of Parentheses/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn score_of_parentheses(s: String) -> i32 { 6 | Solution::score_of_parentheses_(&s) 7 | } 8 | 9 | fn score_of_parentheses_(s: &str) -> i32 { 10 | let (mut left, mut right) = (0, 0); 11 | let mut level = 0; 12 | let mut score = 0; 13 | while right < s.len() { 14 | if s.as_bytes()[right] == '(' as u8 { 15 | level += 1; 16 | if level == 1 { left = right; } 17 | } else { 18 | level -= 1; 19 | if level == 0 { // 找到一对括号 20 | if left + 1 < right { // 嵌套 * 2 21 | score += Solution::score_of_parentheses_(&s[left + 1 .. right]) * 2; 22 | } else { 23 | score += 1; 24 | } 25 | } 26 | } 27 | right += 1; 28 | } 29 | score 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /n0861. Score After Flipping Matrix/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::max; 5 | impl Solution { 6 | pub fn matrix_score(mut a: Vec>) -> i32 { 7 | // 第一列全部翻转为1 8 | a.iter_mut().for_each(|v| { 9 | if v[0] == 0 { 10 | v.iter_mut().for_each(|b| { *b = 1 - *b; }) 11 | } 12 | }); 13 | let mut ans = a.len(); 14 | // 从第二列开始 15 | for i in 1..a[0].len() { 16 | let mut number_of_one = 0; 17 | for j in 0..a.len() { 18 | if a[j][i] == 1 { 19 | number_of_one += 1; 20 | } 21 | } 22 | number_of_one = max(number_of_one, a.len() - number_of_one); 23 | ans = ans * 2 + number_of_one; 24 | } 25 | ans as i32 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /n0876. Middle of the Linked List/README.md: -------------------------------------------------------------------------------- 1 | # Middle of the Linked List :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/middle-of-the-linked-list](https://leetcode-cn.com/problems/middle-of-the-linked-list) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-11 18:34 6 | 7 | ## 题目内容 8 |

给定一个带有头结点 head 的非空单链表,返回链表的中间结点。

9 | 10 |

如果有两个中间结点,则返回第二个中间结点。

11 | 12 | 13 | 14 |

示例 1:

15 | 16 |
输入:[1,2,3,4,5]
17 | 输出:此列表中的结点 3 (序列化形式:[3,4,5])
18 | 返回的结点值为 3 。 (测评系统对该结点序列化表述是 [3,4,5])。
19 | 注意,我们返回了一个 ListNode 类型的对象 ans,这样:
20 | ans.val = 3, ans.next.val = 4, ans.next.next.val = 5, 以及 ans.next.next.next = NULL.
21 | 
22 | 23 |

示例 2:

24 | 25 |
输入:[1,2,3,4,5,6]
26 | 输出:此列表中的结点 4 (序列化形式:[4,5,6])
27 | 由于该列表有两个中间结点,值分别为 3 和 4,我们返回第二个结点。
28 | 
29 | 30 | 31 | 32 |

提示:

33 | 34 |
    35 |
  • 给定链表的结点数介于 1 和 100 之间。
  • 36 |
37 | 38 | 39 | ## 解法 40 | ```rust 41 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 42 | // Zhihu: https://www.zhihu.com/people/netcan 43 | 44 | impl Solution { 45 | pub fn middle_node(mut head: Option>) -> Option> { 46 | let mut pos: i32 = 0; 47 | let mut p = &mut head; 48 | while p.is_some() { 49 | pos += 1; 50 | p = &mut p.as_mut().unwrap().next; 51 | } 52 | pos /= 2; 53 | 54 | p = &mut head; 55 | while p.is_some() { 56 | if pos <= 0 { break; } 57 | pos -= 1; 58 | p = &mut p.as_mut().unwrap().next; 59 | } 60 | p.take() 61 | } 62 | } 63 | 64 | 65 | ``` -------------------------------------------------------------------------------- /n0876. Middle of the Linked List/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn middle_node(mut head: Option>) -> Option> { 6 | let mut pos: i32 = 0; 7 | let mut p = &mut head; 8 | while p.is_some() { 9 | pos += 1; 10 | p = &mut p.as_mut().unwrap().next; 11 | } 12 | pos /= 2; 13 | 14 | p = &mut head; 15 | while p.is_some() { 16 | if pos <= 0 { break; } 17 | pos -= 1; 18 | p = &mut p.as_mut().unwrap().next; 19 | } 20 | p.take() 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /n0877. Stone Game/README.md: -------------------------------------------------------------------------------- 1 | # Stone Game :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/stone-game](https://leetcode-cn.com/problems/stone-game) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-13 23:20 6 | 7 | ## 题目内容 8 |

亚历克斯和李用几堆石子在做游戏。偶数堆石子排成一行,每堆都有正整数颗石子 piles[i] 。

9 | 10 |

游戏以谁手中的石子最多来决出胜负。石子的总数是奇数,所以没有平局。

11 | 12 |

亚历克斯和李轮流进行,亚历克斯先开始。 每回合,玩家从行的开始或结束处取走整堆石头。 这种情况一直持续到没有更多的石子堆为止,此时手中石子最多的玩家获胜。

13 | 14 |

假设亚历克斯和李都发挥出最佳水平,当亚历克斯赢得比赛时返回 true ,当李赢得比赛时返回 false 。

15 | 16 | 17 | 18 |

示例:

19 | 20 |
输入:[5,3,4,5]
21 | 输出:true
22 | 解释:
23 | 亚历克斯先开始,只能拿前 5 颗或后 5 颗石子 。
24 | 假设他取了前 5 颗,这一行就变成了 [3,4,5] 。
25 | 如果李拿走前 3 颗,那么剩下的是 [4,5],亚历克斯拿走后 5 颗赢得 10 分。
26 | 如果李拿走后 5 颗,那么剩下的是 [3,4],亚历克斯拿走后 4 颗赢得 9 分。
27 | 这表明,取前 5 颗石子对亚历克斯来说是一个胜利的举动,所以我们返回 true 。
28 | 
29 | 30 | 31 | 32 |

提示:

33 | 34 |
    35 |
  1. 2 <= piles.length <= 500
  2. 36 |
  3. piles.length 是偶数。
  4. 37 |
  5. 1 <= piles[i] <= 500
  6. 38 |
  7. sum(piles) 是奇数。
  8. 39 |
40 | 41 | 42 | ## 解法 43 | ```rust 44 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 45 | // Zhihu: https://www.zhihu.com/people/netcan 46 | 47 | impl Solution { 48 | pub fn stone_game(piles: Vec) -> bool { 49 | true 50 | } 51 | } 52 | 53 | ``` -------------------------------------------------------------------------------- /n0877. Stone Game/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn stone_game(piles: Vec) -> bool { 6 | true 7 | } 8 | } 9 | -------------------------------------------------------------------------------- /n0902. Numbers At Most N Given Digit Set/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn at_most_n_given_digit_set(digits: Vec, mut num: i32) -> i32 { 6 | let digits: Vec = digits.into_iter().map(|d| d.chars().nth(0).unwrap() as i32 - '0' as i32).collect(); 7 | let num: Vec = num.to_string().as_bytes().into_iter().map(|b| *b as usize - '0' as usize).rev().collect(); 8 | 9 | // 小于数字n的个数 10 | let num_times: Vec = (0..10).map(|d| { 11 | digits.iter().filter(|&n| *n < d).count() as i32 12 | }).collect(); 13 | // 子集中是否存在数字d 14 | let has_digit: Vec = (0..10).map(|d| { 15 | digits.iter().find(|&d2| { *d2 == d }).is_some() as i32 16 | }).collect(); 17 | 18 | // num_combination[n] = (digits.len()) ^ n 19 | let num_combination: Vec = (0..num.len() as u32).map(|n| digits.len().pow(n) as i32).collect(); 20 | // 先从个位到最高位计算 21 | let mut cnt = num_combination[1..num.len()].iter().sum::(); 22 | 23 | // 加上与num同长的个数 24 | let mut cnt2 = 1; 25 | for (idx, &n) in num[0..num.len()].iter().enumerate() { 26 | cnt2 = num_times[n] * num_combination[idx] + has_digit[n] * cnt2; 27 | } 28 | 29 | cnt + cnt2 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /n0922. Sort Array By Parity II/README.md: -------------------------------------------------------------------------------- 1 | # Sort Array By Parity II :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/sort-array-by-parity-ii](https://leetcode-cn.com/problems/sort-array-by-parity-ii) 3 | - 执行时间: 20 ms 4 | - 内存消耗: 3 MB 5 | - 通过日期: 2019-03-06 11:17 6 | 7 | ## 题目内容 8 |

给定一个非负整数数组 A, A 中一半整数是奇数,一半整数是偶数。

9 | 10 |

对数组进行排序,以便当 A[i] 为奇数时,i 也是奇数;当 A[i] 为偶数时, i 也是偶数。

11 | 12 |

你可以返回任何满足上述条件的数组作为答案。

13 | 14 | 15 | 16 |

示例:

17 | 18 |
输入:[4,2,5,7]
19 | 输出:[4,5,2,7]
20 | 解释:[4,7,2,5],[2,5,4,7],[2,7,4,5] 也会被接受。
21 | 
22 | 23 | 24 | 25 |

提示:

26 | 27 |
    28 |
  1. 2 <= A.length <= 20000
  2. 29 |
  3. A.length % 2 == 0
  4. 30 |
  5. 0 <= A[i] <= 1000
  6. 31 |
32 | 33 | 34 | 35 | 36 | ## 解法 37 | ```rust 38 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 39 | // Zhihu: https://www.zhihu.com/people/netcan 40 | 41 | impl Solution { 42 | pub fn sort_array_by_parity_ii(a: Vec) -> Vec { 43 | let mut ret = Vec::with_capacity(a.len()); 44 | unsafe { ret.set_len(a.len()); } 45 | let (mut i, mut j) = (0, 1); 46 | for n in &a { 47 | if n & 1 == 1 { 48 | ret[j] = *n; 49 | j += 2; 50 | } else { 51 | ret[i] = *n; 52 | i += 2; 53 | } 54 | } 55 | ret 56 | } 57 | } 58 | 59 | 60 | ``` -------------------------------------------------------------------------------- /n0922. Sort Array By Parity II/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn sort_array_by_parity_ii(a: Vec) -> Vec { 6 | let mut ret = Vec::with_capacity(a.len()); 7 | unsafe { ret.set_len(a.len()); } 8 | let (mut i, mut j) = (0, 1); 9 | for n in &a { 10 | if n & 1 == 1 { 11 | ret[j] = *n; 12 | j += 2; 13 | } else { 14 | ret[i] = *n; 15 | i += 2; 16 | } 17 | } 18 | ret 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /n0935. Knight Dialer/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn knight_dialer(n: i32) -> i32 { 6 | let n: usize = n as usize; 7 | let NEXT_STEP = vec![ 8 | vec![4, 6], // 0 9 | vec![6, 8], // 1 10 | vec![7, 9], // 2 11 | vec![4, 8], // 3 12 | vec![0, 3, 9], // 4 13 | vec![], // 5 14 | vec![0, 1, 7], // 6 15 | vec![2, 6], // 7 16 | vec![1, 3], // 8 17 | vec![4, 2], // 9 18 | ]; 19 | let mut dp = [[0; 10], [1; 10]]; 20 | for s in 2..=n { 21 | for d in 0..=9 { 22 | dp[s & 1][d] = 0; 23 | for ns in &NEXT_STEP[d] { 24 | dp[s & 1][d] += dp[(s+1) & 1][*ns]; 25 | dp[s & 1][d] %= 1000000007; 26 | } 27 | } 28 | } 29 | // println!("{:#?}", dp); 30 | 31 | dp[n & 1].iter().fold(0, |a, &b| { (a+b) % 1000000007 }) 32 | } 33 | } 34 | 35 | -------------------------------------------------------------------------------- /n0977. Squares of a Sorted Array/README.md: -------------------------------------------------------------------------------- 1 | # Squares of a Sorted Array :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/squares-of-a-sorted-array](https://leetcode-cn.com/problems/squares-of-a-sorted-array) 3 | - 执行时间: 16 ms 4 | - 内存消耗: 3.1 MB 5 | - 通过日期: 2019-03-11 22:29 6 | 7 | ## 题目内容 8 |

给定一个按非递减顺序排序的整数数组 A,返回每个数字的平方组成的新数组,要求也按非递减顺序排序。

9 | 10 | 11 | 12 |

示例 1:

13 | 14 |
输入:[-4,-1,0,3,10]
15 | 输出:[0,1,9,16,100]
16 | 
17 | 18 |

示例 2:

19 | 20 |
输入:[-7,-3,2,3,11]
21 | 输出:[4,9,9,49,121]
22 | 
23 | 24 | 25 | 26 |

提示:

27 | 28 |
    29 |
  1. 1 <= A.length <= 10000
  2. 30 |
  3. -10000 <= A[i] <= 10000
  4. 31 |
  5. A 已按非递减顺序排序。
  6. 32 |
33 | 34 | 35 | ## 解法 36 | ```rust 37 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 38 | // Zhihu: https://www.zhihu.com/people/netcan 39 | 40 | impl Solution { 41 | pub fn sorted_squares(a: Vec) -> Vec { 42 | let mut a = a.iter().map(|&x| x * x).collect::>(); 43 | a.sort(); 44 | a 45 | } 46 | } 47 | 48 | ``` -------------------------------------------------------------------------------- /n0977. Squares of a Sorted Array/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn sorted_squares(a: Vec) -> Vec { 6 | let mut a = a.iter().map(|&x| x * x).collect::>(); 7 | a.sort(); 8 | a 9 | } 10 | } 11 | -------------------------------------------------------------------------------- /n0982. Triples with Bitwise AND Equal To Zero/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn count_triplets(nums: Vec) -> i32 { 6 | let max_num = nums.iter().skip(1).fold(nums[0], |a, b| { a.max(*b) } ) as usize; 7 | // dp[n] 为A[i] & A[j] = n的个数 8 | let mut dp = vec![0; max_num + 1]; 9 | for ai in &nums { 10 | for aj in &nums { dp[(ai & aj) as usize] += 1; } 11 | } 12 | 13 | let mut ans = 0; 14 | for a in &nums { 15 | for b in (0..=max_num as i32) { 16 | if a & b == 0 { 17 | ans += dp[b as usize]; 18 | } 19 | } 20 | } 21 | 22 | ans 23 | } 24 | } 25 | 26 | -------------------------------------------------------------------------------- /n0983. Minimum Cost For Tickets/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::cmp::min; 5 | impl Solution { 6 | pub fn mincost_tickets(days: Vec, costs: Vec) -> i32 { 7 | // dp[day]: 第day天所花费的最小票价 8 | // dp[day] = min(dp[day-1]+costs[0], dp[day-7]+costs[1], dp[day-30]+costs[2]) 9 | let mut travel = [false; 366]; 10 | let mut dp = [0; 366]; 11 | let (first, last) = (*days.first().unwrap(), *days.last().unwrap()); 12 | for day in days { travel[day as usize] = true; } 13 | 14 | for day in first..=last { 15 | dp[day as usize] = if travel[day as usize] { 16 | min(dp[(day - 1) as usize] + costs[0], min( 17 | dp[(day - 7).max(0) as usize] + costs[1], 18 | dp[(day - 30).max(0) as usize] + costs[2], 19 | )) 20 | } else { 21 | dp[(day - 1) as usize] 22 | } 23 | } 24 | 25 | dp[last as usize] 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /n0991. Broken Calculator/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn broken_calc(x: i32, mut y: i32) -> i32 { 6 | if (x >= y) { return x - y; } 7 | let mut step = 0; 8 | while y >= 0 { 9 | if y % 2 == 0 { 10 | y /= 2; 11 | step += 1; 12 | } else { 13 | y = y / 2 + 1; 14 | step += 2; 15 | } 16 | if x >= y { return step + x - y; } 17 | } 18 | step 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /n0995. Minimum Number of K Consecutive Bit Flips/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn min_k_bit_flips(a: Vec, k: i32) -> i32 { 6 | let (mut sum, mut ans) = (0, 0); 7 | // 是否翻转? 8 | let mut flip = vec![0; a.len()]; 9 | for i in 0..a.len() - k as usize + 1 { 10 | if (sum + a[i]) % 2 == 0 { 11 | flip[i] = 1; 12 | sum += flip[i]; 13 | ans += 1; 14 | } 15 | 16 | if i as i32 - k + 1 >= 0 { 17 | sum -= flip[(i as i32 - k + 1) as usize] 18 | } 19 | } 20 | // 检查后面部分,看看是否全部翻转成功 21 | for i in a.len() - k as usize + 1..a.len() { 22 | if (sum + a[i]) % 2 == 0 { 23 | return -1; 24 | } 25 | if i as i32 - k + 1 >= 0 { 26 | sum -= flip[(i as i32 - k + 1) as usize] 27 | } 28 | } 29 | ans 30 | } 31 | } 32 | 33 | #[cfg(test)] 34 | mod tests { 35 | use super::*; 36 | #[test] 37 | fn test_1() { 38 | assert_eq!(Solution::min_k_bit_flips(vec![1, 1, 0], 3), -1); 39 | } 40 | #[test] 41 | fn test_2() { 42 | assert_eq!(Solution::min_k_bit_flips(vec![0,0,0,1,0,1,1,0], 3), 3); 43 | } 44 | #[test] 45 | fn test_3() { 46 | assert_eq!(Solution::min_k_bit_flips(vec![0, 1, 1], 2), -1); 47 | } 48 | #[test] 49 | fn test_4() { 50 | assert_eq!(Solution::min_k_bit_flips(vec![0, 1, 0], 1), 2); 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /n1000. Minimum Cost to Merge Stones/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::iter; 5 | impl Solution { 6 | pub fn merge_stones(stones: Vec, K: i32) -> i32 { 7 | // 检查是否有解 8 | let n = stones.len(); 9 | if (2 - K - n as i32) % (1 - K) != 0 { return -1; } 10 | else if n == 1 { return 0; } 11 | 12 | let mut sumCoin = vec![0; n + 1]; 13 | for (i, stone) in stones.iter().enumerate() { 14 | sumCoin[i + 1] = sumCoin[i] + stone; 15 | } 16 | 17 | // dp[i][j][k]: 将i到j区间的石头合并成k块需要的最小代价 18 | // dp[i][j][k] = min(dp[i][j][k], dp[i][t][k-1] + dp[t+1][j][1]) k > 2 19 | // dp[i][j][1] = dp[i][j][K] + sumCoin[i][j] 20 | let mut dp: Vec>> = iter::repeat( 21 | iter::repeat(vec![100000; K as usize + 1]).take(n + 1).collect() 22 | ).take(n + 1).collect(); 23 | 24 | for i in 1..=n { dp[i][i][1] = 0; } 25 | 26 | for step in 1..n as usize { 27 | for i in 1..=(n - step) as usize { 28 | let j = i + step; 29 | for k in 2..=K as usize { 30 | for t in i..j { 31 | dp[i][j][k] = dp[i][j][k].min(dp[i][t][k-1] + dp[t+1][j][1]); 32 | } 33 | } 34 | // k块合成1块等于k块的代价 + 最后所有的和 35 | dp[i][j][1] = dp[i][j][K as usize] + sumCoin[j] - sumCoin[i - 1]; 36 | } 37 | } 38 | 39 | dp[1][n][1] 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /n1004. Max Consecutive Ones III/README.md: -------------------------------------------------------------------------------- 1 | # Max Consecutive Ones III :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/max-consecutive-ones-iii](https://leetcode-cn.com/problems/max-consecutive-ones-iii) 3 | - 执行时间: 12 ms 4 | - 内存消耗: 3.3 MB 5 | - 通过日期: 2019-03-18 11:35 6 | 7 | ## 题目内容 8 |

给定一个由若干 01 组成的数组 A,我们最多可以将 K 个值从 0 变成 1 。

9 | 10 |

返回仅包含 1 的最长(连续)子数组的长度。

11 | 12 | 13 | 14 |

示例 1:

15 | 16 |
输入:A = [1,1,1,0,0,0,1,1,1,1,0], K = 2
17 | 输出:6
18 | 解释: 
19 | [1,1,1,0,0,1,1,1,1,1,1]
20 | 粗体数字从 0 翻转到 1,最长的子数组长度为 6。
21 | 22 |

示例 2:

23 | 24 |
输入:A = [0,0,1,1,0,0,1,1,1,0,1,1,0,0,0,1,1,1,1], K = 3
25 | 输出:10
26 | 解释:
27 | [0,0,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1]
28 | 粗体数字从 0 翻转到 1,最长的子数组长度为 10。
29 | 30 | 31 | 32 |

提示:

33 | 34 |
    35 |
  1. 1 <= A.length <= 20000
  2. 36 |
  3. 0 <= K <= A.length
  4. 37 |
  5. A[i] 为 0 或 1 
  6. 38 |
39 | 40 | 41 | ## 解法 42 | ```rust 43 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 44 | // Zhihu: https://www.zhihu.com/people/netcan 45 | 46 | use std::collections::VecDeque; 47 | impl Solution { 48 | pub fn longest_ones(a: Vec, mut k: i32) -> i32 { 49 | let mut zeroes = VecDeque::new(); 50 | let mut ans = 0; 51 | let mut i = 0; 52 | for j in 0..a.len() { 53 | if a[j] == 0 { 54 | zeroes.push_back(j); 55 | if zeroes.len() > k as usize { 56 | i = zeroes.pop_front().unwrap() + 1; 57 | } 58 | } 59 | 60 | ans = ans.max(j - i + 1); 61 | } 62 | 63 | ans as i32 64 | } 65 | } 66 | 67 | 68 | ``` -------------------------------------------------------------------------------- /n1004. Max Consecutive Ones III/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::VecDeque; 5 | impl Solution { 6 | pub fn longest_ones(a: Vec, mut k: i32) -> i32 { 7 | let mut zeroes = VecDeque::new(); 8 | let mut ans = 0; 9 | let mut i = 0; 10 | for j in 0..a.len() { 11 | if a[j] == 0 { 12 | zeroes.push_back(j); 13 | if zeroes.len() > k as usize { 14 | i = zeroes.pop_front().unwrap() + 1; 15 | } 16 | } 17 | 18 | ans = ans.max(j - i + 1); 19 | } 20 | 21 | ans as i32 22 | } 23 | } 24 | 25 | -------------------------------------------------------------------------------- /n1005. Maximize Sum Of Array After K Negations/README.md: -------------------------------------------------------------------------------- 1 | # Maximize Sum Of Array After K Negations :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations](https://leetcode-cn.com/problems/maximize-sum-of-array-after-k-negations) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-13 22:41 6 | 7 | ## 题目内容 8 |

给定一个整数数组 A,我们只能用以下方法修改该数组:我们选择某个个索引 i 并将 A[i] 替换为 -A[i],然后总共重复这个过程 K 次。(我们可以多次选择同一个索引 i。)

9 | 10 |

以这种方式修改数组后,返回数组可能的最大和。

11 | 12 | 13 | 14 |

示例 1:

15 | 16 |
输入:A = [4,2,3], K = 1
17 | 输出:5
18 | 解释:选择索引 (1,) ,然后 A 变为 [4,-2,3]。
19 | 
20 | 21 |

示例 2:

22 | 23 |
输入:A = [3,-1,0,2], K = 3
24 | 输出:6
25 | 解释:选择索引 (1, 2, 2) ,然后 A 变为 [3,1,0,2]。
26 | 
27 | 28 |

示例 3:

29 | 30 |
输入:A = [2,-3,-1,5,-4], K = 2
31 | 输出:13
32 | 解释:选择索引 (1, 4) ,然后 A 变为 [2,3,-1,5,4]。
33 | 
34 | 35 | 36 | 37 |

提示:

38 | 39 |
    40 |
  1. 1 <= A.length <= 10000
  2. 41 |
  3. 1 <= K <= 10000
  4. 42 |
  5. -100 <= A[i] <= 100
  6. 43 |
44 | 45 | 46 | ## 解法 47 | ```rust 48 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 49 | // Zhihu: https://www.zhihu.com/people/netcan 50 | 51 | impl Solution { 52 | pub fn largest_sum_after_k_negations(mut a: Vec, k: i32) -> i32 { 53 | a.sort(); 54 | let b = a.clone(); 55 | 56 | let mut j = 0; 57 | for _ in 0..k { 58 | a[j] = -a[j]; 59 | if b[j] < 0 && j + 1 < a.len() { 60 | if b[j + 1] <= 0 || -b[j] > b[j + 1] { 61 | j += 1; 62 | } 63 | } 64 | } 65 | a.iter().sum() 66 | } 67 | } 68 | 69 | ``` -------------------------------------------------------------------------------- /n1005. Maximize Sum Of Array After K Negations/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn largest_sum_after_k_negations(mut a: Vec, k: i32) -> i32 { 6 | a.sort(); 7 | let b = a.clone(); 8 | 9 | let mut j = 0; 10 | for _ in 0..k { 11 | a[j] = -a[j]; 12 | if b[j] < 0 && j + 1 < a.len() { 13 | if b[j + 1] <= 0 || -b[j] > b[j + 1] { 14 | j += 1; 15 | } 16 | } 17 | } 18 | a.iter().sum() 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /n1006. Clumsy Factorial/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn clumsy(n: i32) -> i32 { 6 | let mut op_idx = 0; 7 | let mut seq: Vec = vec![n]; 8 | 9 | // 先算乘除 10 | for i in (1..=n-1).rev() { 11 | if op_idx == 0 { 12 | let j = seq.pop().unwrap(); 13 | seq.push(j * i); 14 | } else if op_idx == 1 { 15 | let j = seq.pop().unwrap(); 16 | seq.push(j / i); 17 | } else { 18 | seq.push(i); 19 | } 20 | op_idx = (op_idx + 1) % 4; 21 | } 22 | 23 | // 后算加减 24 | seq.iter().skip(1).enumerate().fold(seq[0], |acc, (idx, x)| { 25 | if idx % 2 == 0 { acc + x } // + 26 | else { acc - x } // - 27 | }) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /n1007. Minimum Domino Rotations For Equal Row/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::mem::swap; 5 | impl Solution { 6 | pub fn min_domino_rotations(mut a: Vec, mut b: Vec) -> i32 { 7 | let mut ans = -1; 8 | for point in (1..=6) { 9 | for _ in 0..2 { 10 | let mut swap_times = 0; 11 | for (i, j) in a.iter().zip(b.iter()) { 12 | if *i == point { continue; } 13 | else if *j == point { swap_times += 1; } 14 | else { swap_times = -1; break; } 15 | } 16 | if swap_times != -1 && (ans == -1 || ans > swap_times) { 17 | ans = swap_times; 18 | } 19 | swap(&mut a, &mut b); 20 | } 21 | } 22 | ans 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /n1008. Construct Binary Search Tree from Preorder Traversal/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn bst_from_preorder(preorder: Vec) -> Option>> { 8 | if preorder.len() == 0 { 9 | return None; 10 | } 11 | let val = preorder[0]; 12 | let lvals = preorder.iter().skip(1).filter(|&x| { *x < val }).cloned().collect(); 13 | let rvals = preorder.iter().skip(1).filter(|&x| { *x > val }).cloned().collect(); 14 | let mut node = TreeNode::new(val); 15 | node.left = Solution::bst_from_preorder(lvals); 16 | node.right = Solution::bst_from_preorder(rvals); 17 | 18 | Some(Rc::new(RefCell::new(node))) 19 | } 20 | } 21 | 22 | -------------------------------------------------------------------------------- /n1009. Complement of Base 10 Integer/README.md: -------------------------------------------------------------------------------- 1 | # Complement of Base 10 Integer :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/complement-of-base-10-integer](https://leetcode-cn.com/problems/complement-of-base-10-integer) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-03-17 16:04 6 | 7 | ## 题目内容 8 |

每个非负整数 N 都有其二进制表示。例如, 5 可以被表示为二进制 "101"11 可以用二进制 "1011" 表示,依此类推。注意,除 N = 0 外,任何二进制表示中都不含前导零。

9 | 10 |

二进制的反码表示是将每个 1 改为 0 且每个 0 变为 1。例如,二进制数 "101" 的二进制反码为 "010"

11 | 12 |

给定十进制数 N,返回其二进制表示的反码所对应的十进制整数。

13 | 14 | 15 | 16 |
    17 |
18 | 19 |

示例 1:

20 | 21 |
输入:5
22 | 输出:2
23 | 解释:5 的二进制表示为 "101",其二进制反码为 "010",也就是十进制中的 2 。
24 | 
25 | 26 |

示例 2:

27 | 28 |
输入:7
29 | 输出:0
30 | 解释:7 的二进制表示为 "111",其二进制反码为 "000",也就是十进制中的 0 。
31 | 
32 | 33 |

示例 3:

34 | 35 |
输入:10
36 | 输出:5
37 | 解释:10 的二进制表示为 "1010",其二进制反码为 "0101",也就是十进制中的 5 。
38 | 
39 | 40 | 41 | 42 |

提示:

43 | 44 |
    45 |
  1. 0 <= N < 10^9
  2. 46 |
47 | 48 | 49 | ## 解法 50 | ```rust 51 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 52 | // Zhihu: https://www.zhihu.com/people/netcan 53 | 54 | impl Solution { 55 | pub fn bitwise_complement(n: i32) -> i32 { 56 | if n == 0 { return 1; } 57 | let mut n_ = 1; 58 | while n_ < n { n_ <<= 1; } 59 | !n & (n_ - 1) 60 | } 61 | } 62 | 63 | ``` -------------------------------------------------------------------------------- /n1009. Complement of Base 10 Integer/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn bitwise_complement(n: i32) -> i32 { 6 | if n == 0 { return 1; } 7 | let mut n_ = 1; 8 | while n_ < n { n_ <<= 1; } 9 | !n & (n_ - 1) 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /n1010. Pairs of Songs With Total Durations Divisible by 60/README.md: -------------------------------------------------------------------------------- 1 | # Pairs of Songs With Total Durations Divisible by 60 :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60](https://leetcode-cn.com/problems/pairs-of-songs-with-total-durations-divisible-by-60) 3 | - 执行时间: 8 ms 4 | - 内存消耗: 3.4 MB 5 | - 通过日期: 2019-03-17 16:16 6 | 7 | ## 题目内容 8 |

在歌曲列表中,第 i 首歌曲的持续时间为 time[i] 秒。

9 | 10 |

返回其总持续时间(以秒为单位)可被 60 整除的歌曲对的数量。形式上,我们希望索引的数字  i < j 且有 (time[i] + time[j]) % 60 == 0

11 | 12 | 13 | 14 |

示例 1:

15 | 16 |
输入:[30,20,150,100,40]
17 | 输出:3
18 | 解释:这三对的总持续时间可被 60 整数:
19 | (time[0] = 30, time[2] = 150): 总持续时间 180
20 | (time[1] = 20, time[3] = 100): 总持续时间 120
21 | (time[1] = 20, time[4] = 40): 总持续时间 60
22 | 
23 | 24 |

示例 2:

25 | 26 |
输入:[60,60,60]
27 | 输出:3
28 | 解释:所有三对的总持续时间都是 120,可以被 60 整数。
29 | 
30 | 31 | 32 | 33 |

提示:

34 | 35 |
    36 |
  1. 1 <= time.length <= 60000
  2. 37 |
  3. 1 <= time[i] <= 500
  4. 38 |
39 | 40 | 41 | ## 解法 42 | ```rust 43 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 44 | // Zhihu: https://www.zhihu.com/people/netcan 45 | 46 | impl Solution { 47 | pub fn num_pairs_divisible_by60(time: Vec) -> i32 { 48 | let mut cnt = 0; 49 | let mut pair = [0; 60]; 50 | for t in &time { 51 | cnt += pair[((60 - t % 60) % 60) as usize]; 52 | pair[(t % 60) as usize] += 1; 53 | } 54 | cnt 55 | } 56 | } 57 | 58 | ``` -------------------------------------------------------------------------------- /n1010. Pairs of Songs With Total Durations Divisible by 60/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn num_pairs_divisible_by60(time: Vec) -> i32 { 6 | let mut cnt = 0; 7 | let mut pair = [0; 60]; 8 | for t in &time { 9 | cnt += pair[((60 - t % 60) % 60) as usize]; 10 | pair[(t % 60) as usize] += 1; 11 | } 12 | cnt 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /n1011. Capacity To Ship Packages Within D Days/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn ship_within_days(weights: Vec, d: i32) -> i32 { 6 | let max_weight:i32 = *weights.iter().max().unwrap(); 7 | let sum_weight:i32 = weights.iter().sum(); 8 | 9 | let (mut lb, mut ub) = (max_weight, sum_weight + 1); 10 | while ub - lb > 1 { 11 | let mid = (lb + ub) / 2; 12 | if Solution::check_weight(&weights, mid, d) { ub = mid; } 13 | else { lb = mid; } 14 | } 15 | 16 | if Solution::check_weight(&weights, lb, d) { lb } 17 | else { ub } 18 | } 19 | 20 | fn check_weight(weights: &Vec, min_weight: i32, d: i32) -> bool { 21 | let mut curd = 0; 22 | let mut weight = 0; 23 | for w in weights { 24 | if weight + w > min_weight { 25 | weight = *w; 26 | curd += 1; 27 | } else { 28 | weight += w; 29 | } 30 | if curd >= d { return false; }; 31 | } 32 | 33 | return true; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /n1013. Partition Array Into Three Parts With Equal Sum/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn can_three_parts_equal_sum(a: Vec) -> bool { 6 | if a.len() < 3 { return false; } 7 | let sum = a.iter().sum::() / 3; 8 | 9 | let mut p = [0; 3]; // equal part 10 | let mut i = 0; 11 | for k in 0..3 { 12 | while i < a.len() { 13 | p[k] += a[i]; 14 | if p[k] == sum { i += 1; break; } 15 | i += 1; 16 | } 17 | } 18 | return p[0] == p[1] && p[1] == p[2] && p[2] == sum; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /n1014. Best Sightseeing Pair/README.md: -------------------------------------------------------------------------------- 1 | # Best Sightseeing Pair :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/best-sightseeing-pair](https://leetcode-cn.com/problems/best-sightseeing-pair) 3 | - 执行时间: 8 ms 4 | - 内存消耗: 3.5 MB 5 | - 通过日期: 2019-04-02 17:10 6 | 7 | ## 题目内容 8 |

给定正整数数组 AA[i] 表示第 i 个观光景点的评分,并且两个景点 i 和 j 之间的距离为 j - i

9 | 10 |

一对景点(i < j)组成的观光组合的得分为(A[i] + A[j] + i - j):景点的评分之和减去它们两者之间的距离。

11 | 12 |

返回一对观光景点能取得的最高分。

13 | 14 | 15 | 16 |

示例:

17 | 18 |
输入:[8,1,5,2,6]
19 | 输出:11
20 | 解释:i = 0, j = 2, A[i] + A[j] + i - j = 8 + 5 + 0 - 2 = 11
21 | 
22 | 23 | 24 | 25 |

提示:

26 | 27 |
    28 |
  1. 2 <= A.length <= 50000
  2. 29 |
  3. 1 <= A[i] <= 1000
  4. 30 |
31 | 32 | 33 | ## 解法 34 | ```rust 35 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 36 | // Zhihu: https://www.zhihu.com/people/netcan 37 | 38 | impl Solution { 39 | pub fn max_score_sightseeing_pair(a: Vec) -> i32 { 40 | let (mut max_score, mut max_pair) = (0, 0); 41 | for i in 0..a.len() { 42 | max_score = (a[i] - i as i32 + max_pair).max(max_score); 43 | max_pair = max_pair.max(a[i] + i as i32); 44 | } 45 | 46 | max_score 47 | } 48 | } 49 | 50 | 51 | ``` -------------------------------------------------------------------------------- /n1014. Best Sightseeing Pair/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn max_score_sightseeing_pair(a: Vec) -> i32 { 6 | let (mut max_score, mut max_pair) = (0, 0); 7 | for i in 0..a.len() { 8 | max_score = (a[i] - i as i32 + max_pair).max(max_score); 9 | max_pair = max_pair.max(a[i] + i as i32); 10 | } 11 | 12 | max_score 13 | } 14 | } 15 | 16 | -------------------------------------------------------------------------------- /n1015. Smallest Integer Divisible by K/README.md: -------------------------------------------------------------------------------- 1 | # Smallest Integer Divisible by K :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/smallest-integer-divisible-by-k](https://leetcode-cn.com/problems/smallest-integer-divisible-by-k) 3 | - 执行时间: 32 ms 4 | - 内存消耗: 2.4 MB 5 | - 通过日期: 2019-04-02 18:37 6 | 7 | ## 题目内容 8 |

给定正整数 K,你需要找出可以被 K 整除的、仅包含数字 1 的最小正整数 N。

9 | 10 |

返回 N 的长度。如果不存在这样的 N,就返回 -1

11 | 12 | 13 | 14 |

示例 1:

15 | 16 |
输入:1
17 | 输出:1
18 | 解释:最小的答案是 N = 1,其长度为 1。
19 | 20 |

示例 2:

21 | 22 |
输入:2
23 | 输出:-1
24 | 解释:不存在可被 2 整除的正整数 N 。
25 | 26 |

示例 3:

27 | 28 |
输入:3
29 | 输出:3
30 | 解释:最小的答案是 N = 111,其长度为 3。
31 | 32 | 33 | 34 |

提示:

35 | 36 |
    37 |
  • 1 <= K <= 10^5
  • 38 |
39 | 40 | 41 | ## 解法 42 | ```rust 43 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 44 | // Zhihu: https://www.zhihu.com/people/netcan 45 | 46 | impl Solution { 47 | pub fn smallest_repunit_div_by_k(k: i32) -> i32 { 48 | let (mut num, mut len) = (1, 1); 49 | while num % k != 0 && len < 100000 { 50 | num = (num * 10 + 1) % k; 51 | len += 1; 52 | } 53 | 54 | if num % k == 0 { len } 55 | else { -1 } 56 | } 57 | } 58 | 59 | 60 | ``` -------------------------------------------------------------------------------- /n1015. Smallest Integer Divisible by K/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn smallest_repunit_div_by_k(k: i32) -> i32 { 6 | let (mut num, mut len) = (1, 1); 7 | while num % k != 0 && len < 100000 { 8 | num = (num * 10 + 1) % k; 9 | len += 1; 10 | } 11 | 12 | if num % k == 0 { len } 13 | else { -1 } 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /n1016. Binary String With Substrings Representing 1 To N/README.md: -------------------------------------------------------------------------------- 1 | # Binary String With Substrings Representing 1 To N :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/binary-string-with-substrings-representing-1-to-n](https://leetcode-cn.com/problems/binary-string-with-substrings-representing-1-to-n) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-04-02 19:28 6 | 7 | ## 题目内容 8 |

给定一个二进制字符串 S(一个仅由若干 '0' 和 '1' 构成的字符串)和一个正整数 N,如果对于从 1N 的每个整数 X,其二进制表示都是 S 的子串,就返回 true,否则返回 false

9 | 10 | 11 | 12 |

示例 1:

13 | 14 |
输入:S = "0110", N = 3
15 | 输出:true
16 | 
17 | 18 |

示例 2:

19 | 20 |
输入:S = "0110", N = 4
21 | 输出:false
22 | 
23 | 24 | 25 | 26 |

提示:

27 | 28 |
    29 |
  1. 1 <= S.length <= 1000
  2. 30 |
  3. 1 <= N <= 10^9
  4. 31 |
32 | 33 | 34 | ## 解法 35 | ```rust 36 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 37 | // Zhihu: https://www.zhihu.com/people/netcan 38 | 39 | impl Solution { 40 | pub fn query_string(s: String, n: i32) -> bool { 41 | // 最多有s_len ^ 2种子串 42 | if s.len() * s.len() < n as usize { return false; } 43 | for i in 1..=n { 44 | if let None = s.find(&format!("{:b}", i)) { 45 | return false; 46 | } 47 | } 48 | true 49 | } 50 | } 51 | 52 | 53 | ``` -------------------------------------------------------------------------------- /n1016. Binary String With Substrings Representing 1 To N/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn query_string(s: String, n: i32) -> bool { 6 | // 最多有s_len ^ 2种子串 7 | if s.len() * s.len() < n as usize { return false; } 8 | for i in 1..=n { 9 | if let None = s.find(&format!("{:b}", i)) { 10 | return false; 11 | } 12 | } 13 | true 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /n1017. Convert to Base -2/README.md: -------------------------------------------------------------------------------- 1 | # Convert to Base -2 :star::star: 2 | - 题目地址: [https://leetcode-cn.com/problems/convert-to-base-2](https://leetcode-cn.com/problems/convert-to-base-2) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.5 MB 5 | - 通过日期: 2019-03-31 12:48 6 | 7 | ## 题目内容 8 |

给出数字 N,返回由若干 "0" 和 "1"组成的字符串,该字符串为 N 的负二进制(base -2表示。

9 | 10 |

除非字符串就是 "0",否则返回的字符串中不能含有前导零。

11 | 12 | 13 | 14 |

示例 1:

15 | 16 |
输入:2
17 | 输出:"110"
18 | 解释:(-2) ^ 2 + (-2) ^ 1 = 2
19 | 
20 | 21 |

示例 2:

22 | 23 |
输入:3
24 | 输出:"111"
25 | 解释:(-2) ^ 2 + (-2) ^ 1 + (-2) ^ 0 = 3
26 | 
27 | 28 |

示例 3:

29 | 30 |
输入:4
31 | 输出:"100"
32 | 解释:(-2) ^ 2 = 4
33 | 
34 | 35 | 36 | 37 |

提示:

38 | 39 |
    40 |
  1. 0 <= N <= 10^9
  2. 41 |
42 | 43 | 44 | ## 解法 45 | ```rust 46 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 47 | // Zhihu: https://www.zhihu.com/people/netcan 48 | 49 | impl Solution { 50 | pub fn base_neg2(mut n: i32) -> String { 51 | if n == 0 { return 0.to_string(); } 52 | let mut ans = String::new(); 53 | while n != 0 { 54 | let mut reminder = n % -2; 55 | n /= -2; 56 | if reminder < 0 { 57 | reminder += 2; 58 | n += 1; 59 | } 60 | ans = reminder.to_string() + &ans; 61 | } 62 | 63 | ans 64 | } 65 | } 66 | 67 | ``` -------------------------------------------------------------------------------- /n1017. Convert to Base -2/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn base_neg2(mut n: i32) -> String { 6 | if n == 0 { return 0.to_string(); } 7 | let mut ans = String::new(); 8 | while n != 0 { 9 | let mut reminder = n % -2; 10 | n /= -2; 11 | if reminder < 0 { 12 | reminder += 2; 13 | n += 1; 14 | } 15 | ans = reminder.to_string() + &ans; 16 | } 17 | 18 | ans 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /n1018. Binary Prefix Divisible By 5/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn prefixes_div_by5(a: Vec) -> Vec { 6 | let mut ans = vec![]; 7 | let mut sum = 0; 8 | 9 | for n in a { 10 | sum = (sum * 2 + n) % 5; 11 | ans.push(if sum == 0 { true } 12 | else { false }); 13 | } 14 | 15 | ans 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /n1019. Next Greater Node In Linked List/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn next_larger_nodes(mut head: Option>) -> Vec { 6 | let mut num = vec![]; 7 | while let Some(node) = head { 8 | num.push(node.val); 9 | head = node.next; 10 | } 11 | 12 | 13 | let mut ans = vec![0; num.len()]; 14 | let mut stack = vec![]; 15 | 16 | for i in 0..num.len() { 17 | while stack.len() > 0 && num[*stack.last().unwrap()] < num[i] { 18 | ans[stack.pop().unwrap()] = num[i]; 19 | } 20 | stack.push(i); 21 | } 22 | 23 | ans 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /n1020. Number of Enclaves/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::collections::VecDeque; 5 | use std::iter::repeat; 6 | 7 | impl Solution { 8 | const dxy: [(i32, i32); 4] = [(0 ,1), (0, -1), (-1, 0), (1, 0)]; 9 | pub fn num_enclaves(mut a: Vec>) -> i32 { 10 | let (m, n) = (a.len(), a[0].len()); 11 | 12 | let mut mark: Vec> = repeat(vec![false; n]).take(m).collect(); 13 | let mut que = VecDeque::new(); 14 | 15 | for i in 0..m { 16 | for j in 0..n { 17 | if (i == 0 || j == 0 || i == m - 1 || j == n - 1) && 18 | a[i][j] == 1 { 19 | mark[i][j] = true; 20 | que.push_back((i as i32, j as i32)); 21 | } 22 | } 23 | } 24 | 25 | while !que.is_empty() { 26 | let last_pos = que.pop_front().unwrap(); 27 | for &d in &Solution::dxy { 28 | let next_pos:(i32, i32) = (last_pos.0 + d.0, last_pos.1 + d.1); 29 | if next_pos.0 >= 0 && next_pos.0 < m as i32 && 30 | next_pos.1 >= 0 && next_pos.1 < n as i32 && 31 | a[next_pos.0 as usize][next_pos.1 as usize] == 1 && 32 | !mark[next_pos.0 as usize][next_pos.1 as usize] { 33 | mark[next_pos.0 as usize][next_pos.1 as usize] = true; 34 | que.push_back(next_pos); 35 | } 36 | } 37 | } 38 | 39 | let mut cnt: i32 = 0; 40 | for i in 0..m { 41 | for j in 0..n { 42 | if a[i][j] == 1 && !mark[i][j] { 43 | cnt += 1; 44 | } 45 | } 46 | } 47 | cnt 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /n1021. Remove Outermost Parentheses/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn remove_outer_parentheses(s: String) -> String { 6 | let s = s.into_bytes(); 7 | let mut lev = 0; 8 | let mut primitive = String::new(); 9 | for &p in &s { 10 | if p == '(' as u8 { 11 | if lev > 0 { primitive += "("; } 12 | lev += 1; 13 | } else { // ')' 14 | lev -= 1; 15 | if lev > 0 { primitive += ")"; } 16 | } 17 | } 18 | 19 | primitive 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /n1022. Sum of Root To Leaf Binary Numbers/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | const Mod: i32 = 1000000007; 8 | pub fn sum_root_to_leaf(root: Option>>) -> i32 { 9 | // 后序遍历 10 | Solution::post_order_sum(&root, 0) 11 | } 12 | fn post_order_sum(root: &Option>>, val: i32) -> i32 { 13 | match root { 14 | None => { return 0; } 15 | Some(node) => { 16 | let node = node.borrow(); 17 | if node.left.is_none() && node.right.is_none() { // 叶子 18 | return (val * 2 + node.val) % Solution::Mod; 19 | } 20 | let left_sum = Solution::post_order_sum(&node.left, (val * 2 + node.val) % Solution::Mod); 21 | let right_sum = Solution::post_order_sum(&node.right, (val * 2 + node.val) % Solution::Mod); 22 | return (left_sum + right_sum) % Solution::Mod; 23 | } 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /n1023. Camelcase Matching/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn camel_match(queries: Vec, pattern: String) -> Vec { 6 | let pattern = pattern.into_bytes(); 7 | let mut ans = vec![false; queries.len()]; 8 | let queries: Vec> = queries.into_iter().map(|x| x.into_bytes()).collect(); 9 | for i in 0..queries.len() { 10 | let word = &queries[i]; 11 | let (mut j, mut k) = (0, 0); 12 | while j < word.len() && k < pattern.len() { 13 | if word[j] == pattern[k] { j += 1; k += 1; } 14 | else if word[j] >= 'a' as u8 && word[j] <= 'z' as u8 { j += 1; } 15 | else { break; } 16 | } 17 | while j < word.len() { 18 | if word[j] >= 'a' as u8 && word[j] <= 'z' as u8 { j += 1; } 19 | else { break; } 20 | } 21 | ans[i] = j >= word.len() && k >= pattern.len(); 22 | } 23 | 24 | ans 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /n1024. Video Stitching/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn video_stitching(mut clips: Vec>, t: i32) -> i32 { 6 | clips.sort_by(|a, b| a[0].partial_cmp(&b[0]).unwrap()); 7 | // dp[t]: [0, t]所需要的最少片段数量 8 | // dp[t] = min(dp[s..=t] + 1) 9 | let mut dp = [clips.len() as i32 + 1; 101]; 10 | dp[0] = 0; 11 | for i in 0..clips.len() { 12 | let (s, e) = (clips[i][0], clips[i][1]); 13 | for j in s..=e { 14 | dp[e as usize] = dp[e as usize].min( 15 | dp[j as usize] + 1 16 | ); 17 | } 18 | } 19 | let mut ans = clips.len() as i32 + 1; 20 | for i in t..=100 { 21 | ans = ans.min(dp[i as usize]); 22 | } 23 | 24 | if ans > clips.len() as i32 { -1 } 25 | else { ans } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /n1025. Divisor Game/README.md: -------------------------------------------------------------------------------- 1 | # Divisor Game :star: 2 | - 题目地址: [https://leetcode-cn.com/problems/divisor-game](https://leetcode-cn.com/problems/divisor-game) 3 | - 执行时间: 0 ms 4 | - 内存消耗: 2.3 MB 5 | - 通过日期: 2019-04-14 12:10 6 | 7 | ## 题目内容 8 |

爱丽丝和鲍勃一起玩游戏,他们轮流行动。爱丽丝先手开局。

9 | 10 |

最初,黑板上有一个数字 N 。在每个玩家的回合,玩家需要执行以下操作:

11 | 12 |
    13 |
  • 选出任一 x,满足 0 < x < N 且 N % x == 0 。
  • 14 |
  • N - x 替换黑板上的数字 N
  • 15 |
16 | 17 |

如果玩家无法执行这些操作,就会输掉游戏。

18 | 19 |

只有在爱丽丝在游戏中取得胜利时才返回 True,否则返回 false。假设两个玩家都以最佳状态参与游戏。

20 | 21 | 22 | 23 |
    24 |
25 | 26 |

示例 1:

27 | 28 |
输入:2
29 | 输出:true
30 | 解释:爱丽丝选择 1,鲍勃无法进行操作。
31 | 
32 | 33 |

示例 2:

34 | 35 |
输入:3
36 | 输出:false
37 | 解释:爱丽丝选择 1,鲍勃也选择 1,然后爱丽丝无法进行操作。
38 | 
39 | 40 | 41 | 42 |

提示:

43 | 44 |
    45 |
  1. 1 <= N <= 1000
  2. 46 |
47 | 48 | 49 | ## 解法 50 | ```rust 51 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 52 | // Zhihu: https://www.zhihu.com/people/netcan 53 | 54 | impl Solution { 55 | pub fn divisor_game(n: i32) -> bool { 56 | if n % 2 == 0 { true } 57 | else { false } 58 | } 59 | } 60 | 61 | ``` -------------------------------------------------------------------------------- /n1025. Divisor Game/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn divisor_game(n: i32) -> bool { 6 | if n % 2 == 0 { true } 7 | else { false } 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /n1026. Maximum Difference Between Node and Ancestor/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn max_ancestor_diff(root: Option>>) -> i32 { 8 | let mut max_diff = 0; 9 | Solution::dfs(&root, &mut Vec::new(), &mut max_diff); 10 | max_diff 11 | } 12 | 13 | fn dfs(root: &Option>>, ancestors: &mut Vec, max_diff: &mut i32) { 14 | match root { 15 | None => { return; } 16 | Some(node) => { 17 | let node = node.borrow(); 18 | for ancestor in ancestors.iter() { // 根据祖先列表求出最大值 19 | *max_diff = (ancestor - node.val).abs().max(*max_diff); 20 | } 21 | ancestors.push(node.val); 22 | Solution::dfs(&node.left, ancestors, max_diff); 23 | Solution::dfs(&node.right, ancestors, max_diff); 24 | ancestors.pop(); 25 | } 26 | } 27 | } 28 | } 29 | 30 | -------------------------------------------------------------------------------- /n1027. Longest Arithmetic Sequence/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn longest_arith_seq_length(a: Vec) -> i32 { 6 | let max_diff = *a.iter().max().unwrap() - *a.iter().min().unwrap(); 7 | if max_diff == 0 { return a.len() as i32; } 8 | // dp[i][diff]: 以第i个数为结尾,[0..i]这个子序列以diff为等差的最大长度 9 | // dp[i][diff] = max(dp[i][diff], dp[j][diff] + 1) for j in 0..i 10 | // 考虑到diff可能为负数,所以加个偏移,使其下标diff_idx >= 0 11 | let mut dp = vec![vec![1; (max_diff * 2) as usize + 1]; a.len()]; 12 | let mut ans = 1; 13 | for i in 1..a.len() { 14 | for j in 0..i { 15 | let diff = a[i] - a[j] + max_diff; // 令diff >= 0 16 | dp[i][diff as usize] = dp[i][diff as usize].max(dp[j][diff as usize] + 1); 17 | ans=ans.max(dp[i][diff as usize]); 18 | } 19 | } 20 | 21 | ans 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /n1028. Recover a Tree From Preorder Traversal/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | use std::rc::Rc; 5 | use std::cell::RefCell; 6 | impl Solution { 7 | pub fn recover_from_preorder(s: String) -> Option>> { 8 | let vals: Vec = s.split('-').filter(|x| x.len() > 0).map(|x| x.parse().unwrap()).collect(); 9 | let mut depths: Vec = s.split(char::is_numeric).filter(|x| x.len() > 0).map(|x| x.len() as i32).collect(); 10 | depths.insert(0, 0); // 根节点 11 | 12 | Solution::build_tree(&vals, &depths, 0, 0).0 13 | } 14 | 15 | fn build_tree(vals: &Vec, depths: &Vec, idx: usize, depth: usize) -> (Option>>, usize) { 16 | if idx >= vals.len() || depth as i32 > depths[idx] { 17 | return (None, idx); 18 | } 19 | let child = Some(Rc::new(RefCell::new(TreeNode::new(vals[idx])))); 20 | let (left, left_idx) = Solution::build_tree(vals, depths, idx + 1, depth + 1); 21 | let mut next_idx = left_idx; 22 | child.as_ref().unwrap().borrow_mut().left = left; 23 | if left_idx > idx { // 有右子树 24 | let (right, right_idx) = Solution::build_tree(vals, depths, left_idx, depth + 1); 25 | next_idx = right_idx; 26 | child.as_ref().unwrap().borrow_mut().right = right; 27 | } 28 | 29 | (child, next_idx) 30 | } 31 | } 32 | 33 | -------------------------------------------------------------------------------- /n1033. Moving Stones Until Consecutive/main.rs: -------------------------------------------------------------------------------- 1 | // Author: Netcan @ https://github.com/netcan/Leetcode-Rust 2 | // Zhihu: https://www.zhihu.com/people/netcan 3 | 4 | impl Solution { 5 | pub fn num_moves_stones(a: i32, b: i32, c: i32) -> Vec { 6 | let (a, b) = if a > b { (b, a) } else { (a, b) }; 7 | let (a, c) = if a > c { (c, a) } else { (a, c) }; 8 | let (b, c) = if b > c { (c, b) } else { (b, c) }; 9 | vec![ 10 | if b - a != 2 && c - b != 2 { 11 | (if b - a > 1 { 1 } else { 0 }) + 12 | (if c - b > 1 { 1 } else { 0 }) 13 | } else { 1 }, 14 | c - a - 2 15 | ] 16 | } 17 | } 18 | 19 | --------------------------------------------------------------------------------