问题是我正在迭代两种方法。a“for loop”和
Unit+1
。我有点搞砸了递归的核心。不使用“for loop”,只使用
Unit+1
was all that was needed.
类解决方案{
func rob(unums:[int])->int{
var mostmoneyrobbed=0
func rob(neighborunits:[int],startfromunit:int,didrobajacentunit:bool,totalmoneyrobbed total:int){
如果总数超过大多数,则取消{
mostMoneyRobbed=总计
}
如果单位=neighborunits.count-1{
如果!双机器人相邻单元{
如果总计+nums[单位]>mostmoneyrobbed{
mostmoneyrobbed=总数+数字[单位]
}
}
返回
}
如果是双相邻单元{
rob(neighborunits:nums,startfromunit:unit+1,didrobajacentunit:false,totalmoneyrobbed:total)
}否则{
rob(邻居单位:nums,开始单位:Unit+1,didrobajacentUnit:true,totalmoneyrobbed:total+nums[单位])
rob(neighborunits:nums,startfromunit:unit+1,didrobajacentunit:false,totalmoneyrobbed:total)
}
}
guard nums.count>1其他{
如果nums.count==0{
返回0
}否则{
返回数字[0]
}
}
rob(邻居单位:nums,开始单位:0,didrobajacentUnit:true,totalmoneyrobbed:0)
rob(neighborunits:nums,startfromunit:0,didrobajacentunit:false,totalmoneyrobbed:0)
返回mostmoneyrobbed
}
}
到目前为止,这已达到预期效果。在leetcode上,我得到了一个超过时间限制的第49个测试用例的错误!d
e“for loop”并仅使用单位+1
只需要这些。
class Solution {
func rob(_ nums: [Int]) -> Int {
var mostMoneyRobbed = 0
func rob(neighborUnits: [Int], startfromUnit unit: Int, didRobAdjacentUnit: Bool, totalMoneyRobbed total: Int){
if total > mostMoneyRobbed{
mostMoneyRobbed = total
}
if unit == neighborUnits.count - 1{
if !didRobAdjacentUnit{
if total + nums[unit] > mostMoneyRobbed{
mostMoneyRobbed = total + nums[unit]
}
}
return
}
if didRobAdjacentUnit{
rob(neighborUnits: nums, startfromUnit: unit + 1, didRobAdjacentUnit: false, totalMoneyRobbed: total)
}else{
rob(neighborUnits: nums, startfromUnit: unit + 1, didRobAdjacentUnit: true, totalMoneyRobbed: total + nums[unit])
rob(neighborUnits: nums, startfromUnit: unit + 1, didRobAdjacentUnit: false, totalMoneyRobbed: total)
}
}
guard nums.count > 1 else{
if nums.count == 0{
return 0
}else{
return nums[0]
}
}
rob(neighborUnits: nums, startfromUnit: 0, didRobAdjacentUnit: true, totalMoneyRobbed: 0)
rob(neighborUnits: nums, startfromUnit: 0, didRobAdjacentUnit: false, totalMoneyRobbed: 0)
return mostMoneyRobbed
}
}
到目前为止,这已达到预期效果。在Leetcode上我有一个超过时间限制第49个测试用例出错!D