From f67553296ce2a5b8600ae3358c920b187c10e534 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Tue, 20 Aug 2024 11:58:29 +0800 Subject: [PATCH] 20240820 Finished --- src/problem/mod.rs | 3 +- ..._number_of_ways_to_reach_the_k_th_stair.rs | 56 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) create mode 100644 src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 6e82130..a0c4841 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -210,4 +210,5 @@ mod p3117_minimum_sum_of_values_by_dividing_array; mod p3137_minimum_number_of_operations_to_make_word_k_periodic; mod p551_student_attendance_record_i; -mod p552_student_attendance_record_ii; \ No newline at end of file +mod p552_student_attendance_record_ii; +mod p3154_find_number_of_ways_to_reach_the_k_th_stair; \ No newline at end of file diff --git a/src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs b/src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs new file mode 100644 index 0000000..f52ace6 --- /dev/null +++ b/src/problem/p3154_find_number_of_ways_to_reach_the_k_th_stair.rs @@ -0,0 +1,56 @@ +/** + * [3154] Find Number of Ways to Reach the K-th Stair + */ +pub struct Solution {} + + +// submission codes start here + +impl Solution { + pub fn ways_to_reach_stair(k: i32) -> i32 { + let mut n = 0; + let mut pos = 1; + let mut result = 0; + + loop { + if pos - n - 1 <= k && k <= pos { + result += Self::combine(n + 1, pos - k); + } + + if pos - n - 1 > k { + break; + } + + n += 1; + pos *= 2; + } + + result + } + + /// C_n^k = \frac{n * (n - 1) * .. * (n - k + 1)}{1 * 2 * 3 * ... * k} + fn combine(n : i32, k: i32) -> i32 { + let mut result: i64 = 1; + let (n, k) = (n as i64, k as i64); + + for i in (n - k + 1..=n).rev() { + result *= i; + result /= n - i + 1; + } + + result as i32 + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_3154() { + assert_eq!(2, Solution::ways_to_reach_stair(0)); + assert_eq!(4, Solution::ways_to_reach_stair(1)); + } +}