All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0001_0100.s0046_permutations.Solution.swift Maven / Gradle / Ivy

The newest version!
// #Medium #Top_100_Liked_Questions #Top_Interview_Questions #Array #Backtracking
// #Algorithm_I_Day_11_Recursion_Backtracking #Level_2_Day_20_Brute_Force/Backtracking
// #Udemy_Backtracking/Recursion #Big_O_Time_O(n*n!)_Space_O(n+n!)
// #2024_06_23_Time_8_ms_(86.06%)_Space_15.9_MB_(93.82%)

public class Solution {
    public func permute(_ nums: [Int]) -> [[Int]] {
        if nums.isEmpty {
            return []
        }
        var finalResult = [[Int]]()
        var currResult = [Int]()
        var used = [Bool](repeating: false, count: nums.count)
        permuteRecur(nums, &finalResult, &currResult, &used)
        return finalResult
    }

    private func permuteRecur(_ nums: [Int], _ finalResult: inout [[Int]], _ currResult: inout [Int], _ used: inout [Bool]) {
        if currResult.count == nums.count {
            finalResult.append(currResult)
            return
        }
        for i in 0..




© 2015 - 2025 Weber Informatics LLC | Privacy Policy