★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★
➤微信公衆號:山青詠芝(shanqingyongzhi)
➤博客園地址:山青詠芝(https://www.cnblogs.com/strengthen/)
➤GitHub地址:https://github.com/strengthen/LeetCode
➤原文地址:http://www.javashuo.com/article/p-rqfbfsob-me.html
➤若是連接不是山青詠芝的博客園地址,則多是爬取做者的文章。
➤原文已修改更新!強烈建議點擊原文地址閱讀!支持做者!支持原創!
★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★★html
Given a single positive integer x
, we will write an expression of the form x (op1) x (op2) x (op3) x ...
where each operator op1
, op2
, etc. is either addition, subtraction, multiplication, or division (+
, -
, *
, or /)
. For example, with x = 3
, we might write 3 * 3 / 3 + 3 - 3
which is a value of 3.git
When writing such an expression, we adhere to the following conventions:github
/
) returns rational numbers.-
). For example, "x - x
" is a valid expression as it only uses subtraction, but "-x + x
" is not because it uses negation.We would like to write an expression with the least number of operators such that the expression equals the given target
. Return the least number of expressions used.express
Example 1:微信
Input: x = 3, target = 19 Output: 5 Explanation: 3 * 3 + 3 * 3 + 3 / 3. The expression contains 5 operations.
Example 2:app
Input: x = 5, target = 501 Output: 8 Explanation: 5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5. The expression contains 8 operations.
Example 3:spa
Input: x = 100, target = 100000000 Output: 3 Explanation: 100 * 100 * 100 * 100. The expression contains 3 operations.
Note:code
2 <= x <= 100
1 <= target <= 2 * 10^8
給定一個正整數 x
,咱們將會寫出一個形如 x (op1) x (op2) x (op3) x ...
的表達式,其中每一個運算符 op1
,op2
,… 能夠是加、減、乘、除(+
,-
,*
,或是 /
)之一。例如,對於 x = 3
,咱們能夠寫出表達式 3 * 3 / 3 + 3 - 3
,該式的值爲 3 。orm
在寫這樣的表達式時,咱們須要遵照下面的慣例:htm
/
)返回有理數。-
)。例如,「x - x
」 是一個有效的表達式,由於它只使用減法,可是 「-x + x
」 不是,由於它使用了否認運算符。 咱們但願編寫一個能使表達式等於給定的目標值 target
且運算符最少的表達式。返回所用運算符的最少數量。
示例 1:
輸入:x = 3, target = 19 輸出:5 解釋:3 * 3 + 3 * 3 + 3 / 3 。表達式包含 5 個運算符。
示例 2:
輸入:x = 5, target = 501 輸出:8 解釋:5 * 5 * 5 * 5 - 5 * 5 * 5 + 5 / 5 。表達式包含 8 個運算符。
示例 3:
輸入:x = 100, target = 100000000 輸出:3 解釋:100 * 100 * 100 * 100 。表達式包含 3 個運算符。
提示:
2 <= x <= 100
1 <= target <= 2 * 10^8
100ms
1 class Solution { 2 var x:Int = 0 3 var best:Int = 0 4 func leastOpsExpressTarget(_ x: Int, _ target: Int) -> Int { 5 var target = target 6 self.x = x 7 var list:[Int] = [Int]() 8 while(target != 0) 9 { 10 list.append(target % x) 11 target /= x 12 } 13 self.best = Int.max 14 dfs(list, 0, 0, 0) 15 return best - 1 16 } 17 18 func dfs(_ list:[Int],_ k:Int,_ add:Int,_ count:Int) 19 { 20 var add = add 21 if count >= best 22 { 23 return 24 } 25 if add == 0 && k >= list.count 26 { 27 best = min(best, count) 28 return 29 } 30 31 if k < list.count 32 { 33 add += list[k] 34 } 35 var cost:Int = k == 0 ? 2 : k 36 var cur:Int = add % x 37 add /= x 38 dfs(list, k + 1, add, count + cost * cur) 39 if cur != 0 && k <= list.count + 2 40 { 41 dfs(list, k + 1, 1, count + cost * (x - cur)) 42 } 43 } 44 }