在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★ Given Suppose you triangulate the polygon into Return the smallest possible total score that you can achieve with some triangulation of the polygon. Example 1: Input: [1,2,3]
Output: 6
Explanation: The polygon is already triangulated, and the score of the only triangle is 6.
Example 2: Input: [3,7,4,5]
Output: 144
Explanation: There are two triangulations, with possible scores: 3*7*5 + 4*5*7 = 245, or 3*4*5 + 3*4*7 = 144. The minimum score is 144.
Example 3: Input: [1,3,1,4,1,5]
Output: 13
Explanation: The minimum score triangulation has score 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13.
Note:
给定 假设您将多边形剖分为 返回多边形进行三角剖分后可以得到的最低分。 示例 1: 输入:[1,2,3] 输出:6 解释:多边形已经三角化,唯一三角形的分数为 6。 示例 2: 输入:[3,7,4,5] 输出:144 解释:有两种三角剖分,可能得分分别为:3*7*5 + 4*5*7 = 245,或 3*4*5 + 3*4*7 = 144。最低分数为 144。 示例 3: 输入:[1,3,1,4,1,5] 输出:13 解释:最低分数三角剖分的得分情况为 1*1*3 + 1*1*4 + 1*1*5 + 1*1*1 = 13。 提示:
20ms
1 class Solution { 2 func minScoreTriangulation(_ A: [Int]) -> Int { 3 var dp = Array(repeating: Array(repeating: 0, count: A.count), count: A.count + 1) 4 for size in 3...A.count { 5 for i in 0...A.count - size { 6 if size == 3 { 7 dp[size][i] = A[i] * A[i + 1] * A[i + 2] 8 } else { 9 var result = Int.max 10 11 for other in (i + 1)..<(i + size - 1) { 12 var this = A[i] * A[i + size - 1] * A[other] 13 14 if other > i + 1 { 15 this += dp[other - i + 1][i] 16 } 17 18 if other < i + size - 2 { 19 this += dp[i + size - other][other] 20 } 21 22 result = min(result, this) 23 } 24 25 dp[size][i] = result 26 } 27 } 28 } 29 30 return dp[A.count][0] 31 } 32 } Runtime: 36 ms Memory Usage: 18.8 MB
1 class Solution { 2 func minScoreTriangulation(_ A: [Int]) -> Int { 3 var n:Int = A.count 4 var dp:[[Int]] = [[Int]](repeating:[Int](repeating:0,count:n),count:n) 5 for len in 2..<n 6 { 7 for i in 0..<(n - len) 8 { 9 var j:Int = i + len 10 dp[i][j] = Int.max 11 for k in (i + 1)..<j 12 { 13 dp[i][j] = min(dp[i][j], dp[i][k] + dp[k][j] + A[i]*A[j]*A[k]) 14 } 15 } 16 } 17 return dp[0][n-1] 18 } 19 } 44ms
1 class Solution { 2 func minScoreTriangulation(_ A: [Int]) -> Int { 3 var memo = [[Int]](repeating: [Int](repeating: 0, count: A.count), count:A.count) 4 return dfsHelper(A, 0, A.count - 1, &memo) 5 } 6 7 fileprivate func dfsHelper(_ A:[Int], _ i:Int, _ j: Int, _ memo: inout [[Int]]) -> Int { 8 9 if j < i + 2 { 10 return 0 11 } 12 if memo[i][j] != 0 { 13 return memo[i][j] 14 } 15 var result = Int.max 16 for k in stride(from: i+1, to: j, by: 1) { 17 result = min(result, dfsHelper(A, i, k, &memo) + dfsHelper(A, k, j, &memo) + A[i] * A[k] * A[j]) 18 } 19 memo[i][j] = result 20 return memo[i][j] 21 } 22 }
|
请发表评论