python permutations 与C++ next_permutation 区别

根据python文档:

Elements are treated as unique based on their position, not on their value. So if the input elements are unique, there will be no repeat values in each permutation.

可见python中itertool库中permutations()函数是根据初始参数存放次序决定的,而不是根据值的大小,

而c++的stl库中的next_permutation()函数是根据值的大小全排列.如果初始参数有序,则两种函数结果相同,反之不同

使用python重新写permutations函数,使之与stl中函数功能相同

def next_permutation(n):
    flag=False
    for i in range(len(n)-2,-1,-1):
        if n[i]<n[i+1]:
            flag=True
            break
    if not flag:
        return False
    for j in range(len(n)-1,i,-1):
        if n[j]>n[i]:
            break
    n[i],n[j]=n[j],n[i]
    n[i+1:]=n[:i:-1]
    return True

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值