Make writing a habit together! This is the 7th day of my participation in the “Gold Digging Day New Plan · April More text Challenge”. Click here for more details.
preface
[C] LeetCode 100
Our community will continue to include Yi Gu (Netflix growth hacker, author of The Way to Interview for iOS, ACE professional fitness coach). Swift algorithm problem solving sorted into text version to facilitate everyone to learn and read.
We have updated 62 issues of LeetCode algorithm so far, and we will keep the update time and progress (Monday, Wednesday, Friday 9:00 am release). The content of each issue is not much, we hope you can read it on your way to work, there will be a great improvement in long-term accumulation.
Short step, no thousands of miles; No small streams, no rivers and seas, Swift community with you forward. If you have suggestions and comments welcome to leave a message at the end of the article, we will try our best to meet your needs.
Difficulty level: Medium
1. Describe
A robot is located in the upper left corner of an M x N grid (the starting point is marked “Start” in the figure below).
The robot can only move one step to the right or down at a time. The robot attempts to reach the lower right corner of the grid (marked “Finish” in the image below).
How many different paths are there?
Example 2.
Example 1
Input: m = 3, n = 7 Output: 28Copy the code
Example 2
Input: m = 3, n = 2 Output: 3 Description: There are three paths to the lower right corner starting from the upper left corner. Right -> down -> down 2. Down -> Down -> Right 3. Down -> right -> downCopy the code
Example 3
Input: m = 7, n = 3 Output: 28Copy the code
Example 4
Input: m = 3, n = 3 Output: 6Copy the code
Constraints:
1 <= m, n <= 100
- The problem data guarantees that the answer is less than or equal to
2 * 10 ^ 9
3. The answer
class UniquePaths {
func uniquePaths(m: Int._ n: Int) -> Int {
var pathNums = Array(count: m, repeatedValue: Array(count: n, repeatedValue: 0))
return _helper(&pathNums, m - 1, n - 1)}private func _helper(inout pathNums: [[Int]], _ m: Int._ n: Int) -> Int {
if m < 0 || n < 0 {
return 0
}
if m = = 0 || n = = 0 {
return 1
}
if pathNums[m][n] ! = 0 {
return pathNums[m][n]
}
pathNums[m][n] = _helper(&pathNums, m - 1, n) + _helper(&pathNums, m, n - 1)
return pathNums[m][n]
}
}
Copy the code
- Main idea: 2D dynamic programming, using 2D array as cache to store computational data.
- Time complexity: O(Mn)
- Space complexity: O(Mn)
Leetcode-swift is a repository for solving problems of this algorithm
Click to go to LeetCode practice
About us
We are jointly maintained by Swift enthusiasts. We will share technical content based on Swift combat, SwiftUI and Swift foundation, as well as collect excellent learning materials.
The follow-up will also translate a large number of information to our public account, interested friends, can join us.