Why my recursive solution occur a wrong answer error?it seems like a bug!


  • 0
    H

    The below is the testcase's input and output. When i test in my local environment, my code outputs the correct result [2,1], why the oj's output is [1,2]? it confused me for a long time.

    Input: [1,2]
    Output: [1,2]
    Expected: [2,1]

    here is my python solution, please help for me ,thanks!!

    class Solution:
    # @param num, a list of integer
    # @return nothing (void), do not return anything, modify num in-place instead.
    def nextPermutation(self, num, reverse = [], start = [], stackLayer = 0):
        l = len(num)-stackLayer
        index = -1
        if l == 1:
            reverse.append(1)
        else:
            for i in range(l-2, -1, -1):
                if num[l-1] > num[i]:
                    num[l-1],num[i] = num[i],num[l-1]
                    index = i
                    start.append(index)
                    break
                else:
                    pass
            if index == -1:
                self.nextPermutation(num,reverse,start,stackLayer+1)
                if start != []:
                    index = start[0]
            if reverse != [] and stackLayer == 0:
                for i in range(0,l/2):
                    num[i],num[l-i-1] = num[l-i-1],num[i]
            elif reverse == []:
                for i in range(index+1,l-1):
                    if num[l-1] < num[i]:
                        num[l-1],num[i] = num[i],num[l-1]
                    else:
                        pass

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.