defnext_permutation(nums): n = len(nums) # traversal the list from its end # if find the first pair of numbers that is not inverse,begin to change its positon for i inrange(n-2,-1,-1): if nums[i] < nums[i+1]: # begin to find the first number that are bigger than it for j inrange(n-1,-1,-1): if nums[i] < nums[j]: nums[i], nums[j] = nums[j], nums[i] nums[i+1:] = sorted(nums[i+1:]) # this funtion also run one time break # notice that the function only run one time break return nums
defpre_permutation(nums): n = len(nums) # the traceback action of the former function for i inrange(n-2,-1,-1): if nums[i] > nums[i+1]: for j inrange(n-1,-1,-1): if nums[i] > nums[j]: # swap nums[i], nums[j] = nums[j], nums[i] nums[i+1:] = sorted(nums[i+1:], reverse = True) break break return nums
例题演示
例题一:全排列问题
题目描述:
按照字典序输出自然数 1 到 n 所有不重复的排列,即 n 的全排列,要求所产生的任一数字序列中不允许出现重复的数字。
defdfs(left, visited, path): if left == 0: # all of the number have already been put on its position print(' ', end = '') for i in path: print(i, end = ' ') print() for i inrange(1,n+1): if visited[i]: continue # hasn't been visited path.append(i) left -= 1 visited[i] = True dfs(left, visited, path) # traverse back path.pop() left += 1 visited[i] = False
defadd(): # add one to the number that stored in the list global nums n = len(nums)
if n > 1: # traversal from the end of the list # when find two number that are not inverse,swap the smaller one with the first one that bigger than the number for i inrange(n-2,-1,-1): if nums[i] < nums[i+1]: for j inrange(n-1,-1,-1): if nums[i] < nums[j]: # swap nums[i], nums[j] = nums[j], nums[i] # all of the numbers that behind nums[i] need to be sorted again nums[i+1:] = sorted(nums[i+1:]) break break else: if i == 0: # no suitable answer nums.sort()
n = int(input()) m = int(input()) nums = [int(i) for i ininput().split()] # add the small variable to the current number for i inrange(m): add() for i inrange(len(nums)): print(nums[i],end = ' ')