Python recursive solution. 12 SLOC and 39ms.


  • 0
    V
    class Solution(object):
        def generateMatrix(self, n):
            """
            :type n: int
            :rtype: List[List[int]]
            """
            
            if n == 0:
                return []
            if n == 1:
                return [[1]]
            
            prev_mat = self.generateMatrix(n-2)
            
            mat = [range(1,n+1)]
            
            left = 4*(n-1)
            right = n+1
            
            prev_mat = [[m+left for m in r] for r in prev_mat]
            
            mat += [[left-i]+prev_mat[i]+[right+i] for i in xrange(n-2)]
            
            mat.append(range( left - (n-2), right + (n-2) - 1 , -1 ))
            
            return mat
    '''

Log in to reply
 

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