lintcode brush questions (python) -- permutation and combination

There are many permutation and combination problems in lintcode. If you want to write your own code for these problems, you need to use recursive thinking. .

Like array arrangement, python also has built-in library functions for permutation and combination. It is really cool to use these library functions directly in the process of writing questions.


Arranged function:

import itertools
print(list(itertools.permutations([1,2,3,4],3)))



The above code directly prints the full arrangement of the 3 numbers selected in [1, 2, 3, 4]. If the second parameter is not filled, the default is the length of the array.


Combined functions:

import itertools
print(list(itertools.combinations([1,2,3,4],3)))



Similar to the situation above.


Take the specific topic of lintcode as an example

full array 

Given a list of numbers, return all possible permutations of it.

 Precautions

You can assume there are no repeating numbers.


import itertools
class Solution:
    """
    @param nums: A list of Integers.
    @return: A list of permutations.
    """
    def permute(self, nums):
        # write your code here
        result=[]
        permutation_result=list(itertools.permutations(nums))
        for i in permutation_result:
            result.append(list(i))
        return result


 If written in a non-recursive form, it would look like this:

class Solution:
    """
    @param nums: A list of Integers.
    @return: A list of permutations.
    """
    def permute(self, nums):
        if nums is None:
            return []
        if nums == []:
            return [[]]
        nums = sorted(nums)
        permutation = []
        stack = [-1]
        permutations = []
        while len(stack):
            index = stack.pop()
            index += 1
            while index < len(nums):
                if nums[index] not in permutation:
                    break
                index += 1
            else:
                if len(permutation):
                    permutation.pop()
                continue

            stack.append(index)
            stack.append(-1)
            permutation.append(nums[index])
            if len(permutation) == len(nums):
                permutations.append(list(permutation))
        return permutations




kth permutation 

Given  n  and  k , find 123..nthe  kth  permutation of the permutations formed.

 Precautions

1 ≤ n ≤ 9

Sample

For  n = 3, all permutations are as follows:

123
132
213
231
312
321

如果 k = 4, 第4个排列为,231.

import itertools
class Solution:
    """
    @param n: n
    @param k: the k-th permutation
    @return: a string, the k-th permutation
    """
    def getPermutation(self, n, k):
        result = list(itertools.permutations(range(1,n+1)))[k-1]
        string=""
        for i in result:
            string +=str(i)
        return string


k数和 II 

给定n个不同的正整数,整数k(1<= k <= n)以及一个目标数字。    

在这n个数里面找出K个数,使得这K个数的和等于目标数字,你需要找出所有满足要求的方案。

样例

给出[1,2,3,4],k=2, target=5,返回 [[1,4],[2,3]]

从n个数找出k个数,是组合问题,得到组合后,一个一个和是否为目标数字,即得到结果。

import itertools
class Solution:
    """
    @param A: An integer array.
    @param k: A positive integer (k <= length(A))
    @param target: Integer
    @return a list of lists of integer 
    """
    def kSumII(self, A, k, target):
        # write your code here
        result=list(itertools.combinations(A,k))
        lists=[]
        for i in result:
            if sum(i)==target:
                lists.append(list(i))
        return (lists)

三数之和 

给出一个有n个整数的数组S,在S中找到三个整数a, b, c,找到所有使得a + b + c = 0的三元组。

 注意事项

在三元组(a, b, c),要求a <= b <= c。

结果不能包含重复的三元组。

样例

如S = {-1 0 1 2 -1 -4}, 你需要返回的三元组集合的是:

(-1, 0, 1)

(-1, -1, 2)

import itertools

class Solution:
    """
    @param numbersbers : Give an array numbersbers of n integer
    @return : Find all unique triplets in the array which gives the sum of zero.
    """
    def threeSum(self, numbers):
        """
        首先要对numbers进行清洗,如果numbers中有的数出现了超过两次,则让其最多出现两次。
        例如numbers由100个1和100个-1组成。清洗后的数组的结果和未清洗的结果都是相同的。
        
        但0就不一样了,因为3个0的和也是0,所以0最多可以出现3次
        
        清洗完后,对numbers进行组合,判断组合是否和为0。
        
        注意,返回的结果要按数字大小排序,而且不能有重复的结果。
        """
        CleanNumbers=[]
        setNumbers=set(numbers)
        for i in setNumbers:
            if numbers.count(i)>=2:

                CleanNumbers.append(i)
                CleanNumbers.append(i)
            else:
                CleanNumbers.append(i)
        if numbers.count(0)>=3:
            CleanNumbers.append(0)
        result=[]
        combinations=list(itertools.combinations(CleanNumbers,3))
        for i in combinations:
            if sum(i)==0 and sorted(list(i)) not in result:
                i=list(i)
                i.sort()
                result.append(i)

        return sorted(result)

四数之和 

给一个包含n个数的整数数组S,在S中找到所有使得和为给定整数target的四元组(a, b, c, d)。

 注意事项

四元组(a, b, c, d)中,需要满足a <= b <= c <= d

答案中不可以包含重复的四元组。

样例

例如,对于给定的整数数组S=[1, 0, -1, 0, -2, 2] 和 target=0. 满足要求的四元组集合为:

(-1, 0, 0, 1)

(-2, -1, 1, 2)

(-2, 0, 0, 2)

这道题和上面的三数之和是一模一样的思路,代码如下:

import itertools


class Solution:
    """
    @param numbersbers : Give an array numbersbersbers of n integer
    @param target : you need to find four elements that's sum of target
    @return : Find all unique quadruplets in the array which gives the sum of 
              zero.
    """

    def fourSum(self, numbers, target):
        # write your code here
        setNumbers=set(numbers)
        cleanedNumbers=[]
        for i in setNumbers:
            if numbers.count(i)>=3:
                cleanedNumbers.append(i)
                cleanedNumbers.append(i)
                cleanedNumbers.append(i)
            elif numbers.count(i)==2:
                cleanedNumbers.append(i)
                cleanedNumbers.append(i)
            else:
                cleanedNumbers.append(i)

        if numbers.count(0)>=4:
            cleanedNumbers.append(0)


        result = []
        combinations = list(itertools.combinations(cleanedNumbers, 4))
        for i in combinations:
            if sum(i) == target and sorted(list(i)) not in result:
                result.append(sorted(list(i)))
        return sorted(result)


最接近的三数之和 

给一个包含 n 个整数的数组 S, 找到和与给定整数 target 最接近的三元组,返回这三个数的和。

 注意事项

只需要返回三元组之和,无需返回三元组本身

样例

例如 S = [-1, 2, 1, -4] and target = 1. 和最接近 1 的三元组是 -1 + 2 + 1 = 2.

解析:这道题和上面两道题思路都是一样的,只要用一个变量保存当前的最接近值(贪心算法的思想),最后返回这个最接近值即可。

import itertools
class Solution:
    """
    @param numbers: Give an array numbers of n integer
    @param target : An integer
    @return : return the sum of the three integers, the sum closest target.
    """
    def threeSumClosest(self, numbers, target):
        # write your code here
        cleanedNumbers=[]
        setNumbers=set(numbers)
        for i in setNumbers:
            if numbers.count(i)>=3:
                cleanedNumbers.append(i)
                cleanedNumbers.append(i)
                cleanedNumbers.append(i)
            elif numbers.count(i)==2:
                cleanedNumbers.append(i)
                cleanedNumbers.append(i)
            else:
                cleanedNumbers.append(i)

        combinations = list(itertools.combinations(cleanedNumbers,3))
        minNumber=sum(combinations[0])
        for i in combinations:
            if abs(sum(i)-target)<abs(minNumber-target):
                minNumber=sum(i)
                
        return minNumber
            


带重复元素的排列 

给出一个具有重复数字的列表,找出列表所有不同的排列。

样例

给出列表 [1,2,2],不同的排列有:

[
  [1,2,2],
  [2,1,2],
  [2,2,1]
]
import itertools
class Solution:
    """
    @param nums: A list of integers.
    @return: A list of unique permutations.
    """
    def permuteUnique(self, nums):
        # write your code here
        result=[]
        permutations=list(itertools.permutations(nums))
        for i in permutations:
            if list(i) not in result:
                result.append(list(i))
        return result
    





Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324883749&siteId=291194637