mirror of
https://github.com/krahets/hello-algo.git
synced 2025-11-02 04:31:55 +08:00
Update the code of permutations i and ii
This commit is contained in:
@ -22,22 +22,27 @@ def backtrack(
|
||||
for i, choice in enumerate(choices):
|
||||
# 剪枝:不允许重复选择元素
|
||||
if not selected[i]:
|
||||
# 尝试
|
||||
selected[i] = True # 做出选择
|
||||
state.append(choice) # 更新状态
|
||||
# 尝试:做出选择,更新状态
|
||||
selected[i] = True
|
||||
state.append(choice)
|
||||
backtrack(state, choices, selected, res)
|
||||
# 回退
|
||||
selected[i] = False # 撤销选择
|
||||
state.pop() # 恢复到之前的状态
|
||||
# 回退:撤销选择,恢复到之前的状态
|
||||
selected[i] = False
|
||||
state.pop()
|
||||
|
||||
|
||||
def permutations_i(nums: list[int]) -> list[list[int]]:
|
||||
"""全排列 I"""
|
||||
res = []
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
return res
|
||||
|
||||
|
||||
"""Driver Code"""
|
||||
if __name__ == "__main__":
|
||||
nums = [1, 2, 3]
|
||||
res = []
|
||||
|
||||
# 回溯算法
|
||||
backtrack(state=[], choices=nums, selected=[False] * len(nums), res=res)
|
||||
res = permutations_i(nums)
|
||||
|
||||
print(f"输入数组 nums = {nums}")
|
||||
print(f"所有排列 res = {res}")
|
||||
|
||||
Reference in New Issue
Block a user