Very simple Swift solution (24ms)


  • 0

    The basic idea is that one cell's count is calculated from the lastRow's count + lastCol's count. So the main code of this question has only one line: record[row][col] += record[row-1][col] + record[row][col-1]. Below is my answer:

    func uniquePaths(m: Int, _ n: Int) -> Int {
        var record = Array(count: m+1, repeatedValue: Array(count: n+1, repeatedValue: 0))
        var i = 1, j = 1
        while i <= n {
            record[1][i] = 1
            i += 1
        }
        while j <= m {
            record[j][1] = 1
            j += 1
        }
        var row = 2
        while row <= m {
            var col = 2
            while col <= n {
                record[row][col] += record[row-1][col] + record[row][col-1]
                col += 1
            }
            row += 1
        }
        return record[m][n]
    }
    

Log in to reply
 

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