问题陈述相当简单:
给定一个整数列表返回非相邻的最大总和 元件。
。例如houseRobber([5,0,0,5]) => 10
和houseRobber([2,1,2]) => 4
我决定采用的一个解决方案有两部分:
生成所有可行的索引列表
(例如[5,0,0,5] => [[0,2],[0,3],[1,3]]
)
确定给定指数集的最大元素总和。
(例如[5,0,0,5],[[0,2],[0,3],[1,3]] => 10
)
所以我出去实施了我的解决方案。我已将脚本包设为main,并包含了我自己的失败测试,以便任何人都可以轻松地在自己的机器上运行它。
package main
import(
"fmt"
)
/*
concat takes 2 arrays of integer arrays and concatonates them.
*/
func concat(a,b [][]int) [][]int{
for _,k := range b{
a = append(a,k)
}
return a
}
/*
helper takes an array of integers inGroup which have been included to a given
sub set and an integer lastHouse which is the maximum index for the array it
returns the array of integer arrays representing all possible sets of indices
for non adjacent elements including the indicies provided in inGroup.
*/
func helper(inGroup []int,lastHouse int) [][]int{
if len(inGroup) == 0 {
return concat(helper([]int{0},lastHouse),helper([]int{1},lastHouse))
}
highest := inGroup[len(inGroup)-1]
if highest <= (lastHouse-3){
return concat(helper(append(inGroup,highest+2),lastHouse),
helper(append(inGroup,highest+3),lastHouse))
}
if highest==lastHouse-2{
return [][]int{append(inGroup,highest+2)}
}
return [][]int{inGroup}
}
/*
saturated is a wrapper function for the helper that does the heavy lifting.
*/
func saturated(n int) [][]int{
return helper([]int{},n-1)
}
/*
Given a list of integers and a list of indicies the subSetSum function returns
the sum of the elements at the given indicies.
*/
func subSetSum(values, indicies []int) int{
ret := 0
for _,k := range indicies{
ret += values[k]
}
return ret
}
/*
houseRobber is the main method, taking an array of numbers and returning an integer,
the max sum of non adjacent elements
*/
func houseRobber(nums []int) int{
if(len(nums) == 0){
return 0
}
if(len(nums) == 1){
return nums[0]
}
combos := saturated(len(nums))
temp := 0
ret := 0
bestCombo := 0
for n,k := range combos{
temp = subSetSum(nums,k)
if temp > ret {
ret = temp
bestCombo = n
}
}
fmt.Println(combos[bestCombo])
return ret
}
func main(){
houseRobber([]int{1,2,3,4,5,6,7,8,9,10,11,12,13,14})
houseRobber([]int{1,2,3,4,5,6,7,8,9,10,11,12,13,
14,15,16,17,18,19,20,21,22,23,24,25,26})
}
打印:[1 3 5 7 9 12 13]
&amp; [1 3 5 7 9 11 13 15 17 20 23 25 25]
因为非相邻指数被确定为具有最大总和。 但等等! 12和13相邻!那是怎么发生的?附加到inGroup数组的唯一内容是最高+2和最高+3,但数组中不包含10或11,那么13如何到达那里?此外,在第二个结果的末尾额外的25也似乎逃脱了我认为应该发生的界限。例如。如果最高+ 2和最高+3是唯一附加的值,那么最高+ 0如何被附加到inGroup?
显然这个错误导致一些测试失败,但问题是 并不是普遍存在,因为大多数测试都通过了。
我相信这里有一个解释,但此刻它正在逃避我。
答案 0 :(得分:1)
您似乎遇到了append
函数的一个微妙问题。
您不应该像在函数中一样使用append
来创建新数组。
而是复制它们并将值附加到复制的数组中。
如果您按照此处的定义将append
的来电替换为copyAndAppend
:
func copyAndAppend(i []int, vals ...int) []int {
j := make([]int, len(i), len(i)+len(vals))
copy(j, i)
return append(j, vals...)
}
您的代码似乎正常运行。
请点击此处了解更多详情: