Unique Paths in Rust

impl Solution {
    pub fn unique_paths(m: i32, n: i32) -> i32 {
        // Create a 2D vector to store the number of paths
        let mut dp: Vec<Vec<i32>> = vec![vec![0; n as usize]; m as usize];

        // Initialize first row and column with 1s
        for i in 0..m {
            dp[i as usize][0] = 1;
        }
        for j in 0..n {
            dp[0][j as usize] = 1;
        }

        // Fill the remaining cells using dynamic programming
        for i in 1..m {
            for j in 1..n {
                dp[i as usize][j as usize] =
                    dp[i as usize - 1][j as usize] + dp[i as usize][j as usize - 1];
            }
        }

        // Return the value at the bottom-right corner
        dp[(m - 1) as usize][(n - 1) as usize]
    }
}

PrevNext