Backtracking

Combination

def combine(nums, k):
    nums.sort()
    combinations = []
    combination = []

    def dfs(start, k):
        if len(nums) - start < k:
            return
        if k <= 0:
            combinations.append(combination[:])
            return
        for idx in xrange(start, len(nums)):
            num = nums[idx]
            if idx > start and num == nums[idx - 1]:
                continue
            combination.append(num)
            dfs(idx + 1, k - 1)
            combination.pop()

    dfs(0, k)
    return combinations

Permutation

def permute(nums):
    nums.sort()
    used = [False] * len(nums)
    permutations = []
    permutation = []

    def dfs():
        if len(permutation) == len(nums):
            permutations.append(permutation[:])
            return
        for idx, num in enumerate(nums):
            if used[idx]:
                continue
            if idx > 0 and num == nums[idx - 1] and not used[idx - 1]:
                continue
            used[idx] = True
            permutation.append(num)
            dfs()
            permutation.pop()
            used[idx] = False

    dfs()
    return permutations

Problems

results matching ""

    No results matching ""