给定一个序列求指定位数的排列组合数

题目:求1到p(p<10)个数中取k(1 样例输入:3 2
样例输出:[1,2],
[1,3],
[2,1],
[2,3],
[3,1],
[3,2],

方法:回溯+深度优先搜索


class Solution:
    def numofSum3(self,candidates, target)->int:
        #回溯组合
        result=[]
        tmp=[]
        candidates.sort()
        visited = [0] * len(candidates)
        self.dfs(result,tmp,candidates,target,visited)
        for i in result:
            print(i)


    def dfs(self,result:list,tmp:list,candidates:list,target,visited:list):
        if len(tmp)==target:
            result.append(list(tmp))
            return
        for i in range(len(candidates)):
            if not visited[i]:
                tmp.append(candidates[i])
                visited[i] = 1
        self.dfs(result,tmp,candidates,target,visited)
                visited[i] = 0
                tmp.pop()
obj=Solution()
a = [1,2,3]
target = 2
obj.numofSum3(a,target)

你可能感兴趣的:(自然语言处理,python,深度学习,算法)