因为是列表中数字组合,所以第一反正是用回溯做:
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'