python next permutation_31. Next Permutation

题目描述

Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

If such arrangement is not possible, it must rearrange it as the lowest possible order (ie, sorted in ascending order).

The replacement must be

Here are some examples. Inputs are in the left-hand column and its corresponding outputs are in the right-hand column.

1,2,3 → 1,3,2

3,2,1 → 1,2,3

1,1,5 → 1,5,1

思路

题目要求是将序列变为字典序大1的序列,如果当前序列字典序最大,则变为字典序最小的序列。

当序列很长时,穷举其字典序及其耗时,因此采用其他方法

We need to find the first pair of two successive numbers a[i]a[i] and a[i-1]a[i−1], from the right, which satisfy a[i] > a[i-1]. Now, no rearrangements to the right of a[i-1] can create a larger permutation since that subarray consists of numbers in descending order. Thus, we need to rearrange the numbers to the right of a[i-1] including itself.

Now, what kind of rearrangement will produce the next larger number? We want to create the permutation just larger than the current one. Therefore, we need to replace the number a[i-1] with the number which is just larger than itself among the numbers lying to its right section, say a[j].

代码

class Solution:

def nextPermutation(self, nums: List[int]) -> None:

"""Do not return anything, modify nums in-place instead."""

i = len(nums) -2

while i>=0 and nums[i+1] <= nums[i]:

i -= 1

if i>= 0 :

j = len(nums) - 1

while j >= 0 and nums[j] <= nums[i]:

j -= 1

self.swap(nums,i,j)

self.reverse(nums,i + 1)

def swap(self,nums,i,j):

temp = nums[i]

nums[i] = nums[j]

nums[j] = temp

def reverse(self,nums,start):

i = start

j = len(nums) -1

while i < j:

self.swap(nums,i,j)

i += 1

j -= 1

#############################################################################

Runtime: 40 ms, faster than 76.17% of Python3 online submissions for Next Permutation.

Memory Usage: 13.9 MB, less than 41.07% of Python3 online submissions for Next Permutation.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
回溯法是一种常见的搜索算法,常用于解决旅行商问题(Traveling Salesman Problem, TSP)等组合优化问题。在Python中,我们可以使用递归的方式来实现回溯法求解TSP。以下是一个简单的例子: ```python import itertools def tsp(cities, start): def is_valid(permutation): return sum(city_distances[permutation[i-1]][permutation[i]] for i in range(1, len(permutation))) == 0 def find_min_distance(permutation, last_city): nonlocal best_distance if last_city == len(permutation) - 1: return city_distances[permutation][last_city] else: min_distance = float('inf') for next_city in range(last_city + 1, len(cities)): new_permutation = permutation.copy() new_permutation.append(next_city) if is_valid(new_permutation): min_distance = min(min_distance, find_min_distance(new_permutation, next_city)) return min_distance # 城市之间的距离矩阵 city_distances = [[cities[i][j] for j in cities] for i in cities] best_distance = float('inf') best_path = None for permutation in itertools.permutations(range(len(cities)), len(cities)): if is_valid(permutation): distance = find_min_distance(permutation, 0) if distance < best_distance: best_distance = distance best_path = permutation return best_distance, [cities[i][j] for i, j in zip(best_path[:-1], best_path[1:])] # 示例用法 cities = [ [(0, 0), (1, 0)], [(1, 0), (2, 0)], [(2, 0), (3, 0)] ] # 假设这是三个城市的位置 start_city = 0 best_distance, optimal_path = tsp(cities, start_city) print(f"最优路径总距离: {best_distance}") print(f"最优路径: {optimal_path}")
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值