题解 | #有重复项数字的全排列#

有重复项数字的全排列

https://www.nowcoder.com/practice/a43a2b986ef34843ac4fdd9159b69863

public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param num int整型一维数组 
     * @return int整型二维数组
     */
    func permuteUnique ( _ num: [Int]) -> [[Int]] {
// write code here
        var nums = num.sorted{$0 < $1}
        var path = [Int]()
        backTracing(nums, &path)
        return res
    }
    var map = [Int:Int]()
    var res = [[Int]]()
    func backTracing(_ nums: [Int], _ path:inout [Int]) {
        //中止条件
        if path.count == nums.count {
            res.append(path)
            return
        }
        //单层递归逻辑
        for (idx,num) in nums.enumerated() {
            if map[idx,default:0] == 1 {
                continue
            }
            //例如[1,1], 当idx为1时,当前数和上一个数相等且上一个位置在此次循环未经使用,说明这是一个新的头,和上个头一样可跳过
            if idx > 0, nums[idx] == nums[idx - 1], map[idx - 1] == 0 {
                continue
            }
            map[idx,default:0] = 1
            path.append(num)
            backTracing(nums,&path)
            map[idx,default:0] = 0
            path.removeLast()
        }
    }
}

全部评论

相关推荐

06-26 15:33
青岛工学院 Java
积极的秋田犬要冲国企:他现在邀请我明天面试
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务