全排列和全组合

def combinations(arr,num):
    def solver(arr,num,ans,cur,s):
        print(s,'cur',cur)
        if len(cur)==num:
            ans.append(cur[::])
            return 
        for i in range(s,len(arr)):
            cur.append(arr[i])
            solver(arr,num,ans,cur,i+1)
            cur.pop()
    ans=[]
    cur=[]
    solver(arr,num,ans,cur,0)
    return ans

def permutation(arr,num):
    def solver(arr,num,ans,cur):
        if len(cur)==num:
            print(cur)
            ans.append(cur[::])
            return 
        for a in arr:
            if a in cur:
                continue
            cur.append(a)
            solver(arr,num,ans,cur)
            cur.pop()

    ans=[]
    cur=[]
    solver(arr,num,ans,cur)
    return ans      

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:
        if len(nums) <= 1:  # 递归终止条件
            return [nums]
        res = []
        for idx, num in enumerate(nums):
            res_nums = nums[:idx] + nums[idx + 1:]  # 确定剩余元素
            for j in self.permute(res_nums):  
                res.append([num] + j)
        return res


if __name__=="__main__":
    #arr = [3,4,5,6,7,9] # 非重复
    arr = [3,4,5,6] # 非重复
    num = 3
    #result = combinations(arr,num)
    result = permutation(arr,num)
    print(result)

输入重复数组如何处理??
posted @   机器狗mo  阅读(127)  评论(0编辑  收藏  举报
努力加载评论中...
点击右上角即可分享
微信分享提示