【面试】今日头条面试算法题——全排列

题目描述:给定一个数字,按照原有数字中的各个位上面的数字进行组合,求出比原有数字大的数中最小的数。例如:1234 -> 1243 ,1243 ->1324 ,1324 -> 1342。

解题思路:
1.先将原有数字中的个,十,百,千…位上面的数字取出来,并进行全排列。
2.将全排列得到的数字再进行可以得到由原来数字组合组成的所有的数字。
3.将第二部得到的数字排序,找出题目要求的数。
代码:

def full_arrage(ls, res_ls, index):
    if index>=len(ls):
        res_ls.append(int(''.join(ls)))
        return
    for i in range(index, len(ls)):
        cur_e1 = ls[index]
        cur_e2 = ls[i]
        ls[i],ls[index] = cur_e1, cur_e2
        full_arrage(ls, res_ls, index+1)
        ls[index] = cur_e1
        ls[i] = cur_e2

def find_target(ls, input):
    for i, e in enumerate(ls):
        if e==input:
            return ls[i+1]

input=3451
ls = list(str(input))
res_ls =[]
full_arrage(ls, res_ls, 0)
res = sorted(res_ls)

print(len(res), res)
target = find_target(res, input)
print(target)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值