【Leetcode】179. Largest Number

因为是列表中数字组合,所以第一反正是用回溯做:
version 1 :

class Solution:
    # @param {integer[]} nums
    # @return {string}
    def largestNumber(self, nums):
        res = [0]
        n = len(nums)
        def dfs(nums,index,path,res,n):
            if index == n and path!='':
                res[0] = max(int(path),res[0])
                return res
            for i in range(len(nums)):
                dfs(nums[:i] + nums[i+1:],index+1,path+str(nums[i]),res,n)
        dfs(nums,0,'',res,n)
        return str(res[0])

但是用回溯做长点的数组就超时了
discuss里的想法是根据字符排序来做。
用到了sort函数里cmp参数

class Solution:
    # @param num, a list of integers
    # @return a string
    def largestNumber(self, num):
        num = [str(x) for x in num]
        num.sort(cmp=lambda x, y: cmp(y+x, x+y))
        return ''.join(num).lstrip('0') or '0'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值