46. Permutations

Description of the Problem

Given an array nums of distinct integers, return all the possible permutations. You can return the answer in any order.

Example 1:

Input: nums = [1,2,3]
Output: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

Example 2:

Input: nums = [0,1]
Output: [[0,1],[1,0]]

Example 3:

Input: nums = [1]
Output: [[1]]

Constraints:

  • 1 <= nums.length <= 6
  • 10 <= nums[i] <= 10 All the integers of nums are unique.

Solution 1 - Utilise the answer from [60. Permutation Sequence]

Tags: Permutation and Combination

Code

impl Solution {
    fn helper_permute(nums: &[i32])->Vec<Vec<i32>>{
        if nums.len() == 0{
            return vec![vec![]];
        }

        if nums.len() == 1{
            return vec![nums.to_vec()];
        }

        let mut return_vec = vec![];

        for i in 0..nums.len(){
            let chosen = nums[i];
            let permutations = Solution::helper_permute(&[&nums[0..i], &nums[i+1..]].concat());

            for perm in permutations {
                let permutations = [ &[chosen] , &perm[..] ].concat();
                return_vec.push(permutations);
            }
        }

        return return_vec;
    }

    pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
        return Solution::helper_permute(&nums);
    }
}

Solution 2 - Reuse the iterator from [31. Next Permutation]

Tags: Permutation and Combination

Code

impl Solution {
    pub fn permute(nums: Vec<i32>) -> Vec<Vec<i32>> {
        let iter: PermutationIterator = PermutationIterator::new(nums);
        let mut ans = vec![];
        for v in iter {
            ans.push(v);
        }
        return ans;
    }
}