给定一个序列求指定位数的排列组合数
程序员文章站
2022-09-21 10:03:08
题目:求1到p(p<10)个数中取k(1int: #回溯组合 result=[] tmp=[] candidates.sort()...
题目:求1到p(p<10)个数中取k(1<k<p)个全部可能的排列。
样例输入: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)
本文地址:https://blog.csdn.net/broccoli2/article/details/108262562
上一篇: 2020华为算法校园招聘(整数拆分问题)