Leetcode的结果错误创建最大数量DP

时间:2019-04-22 00:16:00

标签: python dynamic-programming

leetcode DP问题

https://leetcode.com/problems/create-maximum-number/

我试图为该问题提交以下代码,它说由于错误的结果,代码未能通过以下测试案例。但是,当我使用代码通过的相同测试用例测试代码时,不管为什么会发生这种情况,我都遇到了另一个问题。感谢您的帮助

failed test case
[6,7]
[6,0,4]
5


class Solution(object):
    rec = {}
    nums1 = []
    nums2 = []

    def maxNumber(self, nums1, nums2, k):
        """
        :type nums1: List[int]
        :type nums2: List[int]
        :type k: int
        :rtype: List[int]
        """
        idx1 = 0 
        idx2 = 0 
        self.nums1 = tuple(nums1) 
        self.nums2 = tuple(nums2) 
        return self.recursive(k, idx1, idx2)

    def recursive(self, k, idx1, idx2):
        if k == 0: return []
        elif (k,idx1, idx2) in self.rec: return self.rec[(k,idx1, idx2)] 
        else:
            (val, newIdx1, newIdx2) =  self.maxNumRemainArr(k, idx1, idx2)

            self.rec[(k,idx1, idx2)] = [val]+self.recursive(k-1,newIdx1, newIdx2) if k>1 else [val]
            return self.rec[(k,idx1, idx2)]


    def maxNumRemainArr(self, k, idx1, idx2):
        maxV1 = -1
        temp_id1 = None
        for ix, v in enumerate (self.nums1[idx1:]):
            if len(self.nums1[ix+idx1:])+len(self.nums2[idx2:])<=k-1:break
            elif maxV1<v:
                temp_id1 = ix+idx1
                maxV1 = v

        maxV2 = -1
        temp_id2 = None
        for ix2, v in enumerate (self.nums2[idx2:]):
            if len(self.nums1[idx1:])+len(self.nums2[idx2+ix2:])<=k-1:break
            elif maxV2<v:
                temp_id2 = ix2+idx2
                maxV2 = v

        if maxV2 > maxV1:
            return (maxV2, idx1, temp_id2+1)
        elif maxV2 < maxV1:
            return (maxV1,temp_id1+1, idx2)
        elif maxV2 == maxV1: 
            dm_ary1 = self.recursive(k-1,temp_id1+1, idx2)
            dm_ary2 = self.recursive(k-1,idx1, temp_id2+1)
            dm_v1 = int("".join(str(s) for s in dm_ary1)) if len(dm_ary1)>1 else 0        
            dm_v2 = int("".join(str(s) for s in dm_ary2)) if len(dm_ary2)>1 else 0
            if dm_v1>dm_v2:
                return (maxV1,temp_id1+1, idx2)
            else:
                return (maxV2, idx1, temp_id2+1)

0 个答案:

没有答案