首页 > 编程语言 > 详细

47. Permutation II Leetcode Python

时间:2015-03-27 08:49:21      阅读:242      评论:0      收藏:0      [点我收藏+]

Given a collection of numbers that might contain duplicates, return all possible unique permutations.

For example,
[1,1,2] have the following unique permutations:
[1,1,2][1,2,1], and [2,1,1].

generally finding all permutation will take N! time based on T(n) = n*T(n-1)

this approach we can trim some of the cases, example: num[i] == num[i-1] but we have not yet visit num[i - 1]

so it would be a little less than n! but still np

def backtrack(num, res, val, visit):
        if len(val) == len(num) and :
            res.append(val)
        for i in range(len(num)):
        	if i > 0 and visit[i - 1] == False and num[i - 1] == num[i]:
        		continue
            if visit[i] == False:
                visit[i] = True
                backtrack(num, res, val+[num[i]], visit)
                visit[i] = False
def permuteUnique(num):
    visit = [False for i in range(len(num))]
    res = []
    val = []
    num.sort()
    backtrack(num, res, val, visit)
    return res
num = [1, 3, 1]
print permuteUnique(num)


47. Permutation II Leetcode Python

原文:http://blog.csdn.net/hyperbolechi/article/details/44664573

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!