My 1 line Python solution


  • 3

    Use second parameter n to inidicate colors number.
    So this solution can support not only three colors.

    class Solution:
        # @param {integer[][]} costs
        # @return {integer}
        def minCost(self, costs, n=3):
            tmp = [0] * n
            for i in costs: tmp = [i[j] + min((tmp[j:]+tmp[0:j])[1:]) for j in range(n)]
            return min(tmp)
    

    UPDATE, thanks for @StefanPochmann:

    class Solution:
        # @param {integer[][]} costs
        # @return {integer}
        def minCost(self, costs, n=3):
            tmp = [0] * n
            for i in costs:
                tmp = [i[j] + min(tmp[j+1:]+tmp[0:j]) for j in range(n)]
            return min(tmp)
    

    UPDATE, 1 line solution:

    class Solution:
        # @param {integer[][]} costs
        # @return {integer}
        def minCost(self, costs, n=3):
            return min(reduce(lambda x, y: [y[i] + min(x[i+1:]+x[0:i]) for i in range(n)], costs, [0]*n))

  • 0

    It is nice to consider extensions. Moreover, indexing non-repeating colors by (tmp[j:]+tmp[0:j])[1:] is really clever :-)


  • 0

    I find tmp[:j]+tmp[j+1:] nicer. And I don't like the loop all in one line, that's almost as anti-standard as using _ for valuable values.


  • 0

    update it, thanks!


  • 2
    F

    Dude!
    Why one line?
    To show off something?
    it is bad for reading!


  • 0

    There're other lines version.


Log in to reply
 

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