Skip to content

Files

Latest commit

author
Johnny.Wang
Apr 3, 2025
a89b0e3 · Apr 3, 2025

History

History
72 lines (44 loc) · 1.29 KB

046_permutations.md

File metadata and controls

72 lines (44 loc) · 1.29 KB

46. Permutations




https://leetcode.com/problems/permutations/description/


Topic

  • Array
  • Backtracking



Brain Strom

I remember I did this before in Golang implement link.

just convert to rust language. let try this with backtracking approach, and I think it is gonna be more difficult because of Rust's ownership stuff...


Backtracking

impl Solution {

    pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {

        // create a resut vector.
        let mut results: Vec<Vec<i32>> = vec![];
        let mut nums = nums;

        // call the backtracking function.
        Self::backtracking(&mut results, &mut nums, 0);

        return results;
    }

    fn backtracking(results: &mut Vec<Vec<i32>>, nums: &mut Vec<i32>, idx: usize) {
        

        // if the idx is equal to the length of the nums, copy the vector to the results and return.
        if idx == nums.len() {
            results.push(nums.clone());
            return;
        }

        // do swapping.
        for i in idx..nums.len() {
            nums.swap(idx, i);
            Self::backtracking(results, nums, idx + 1);
            nums.swap(idx, i);
        }
    }

}

pretty ez.