尝试将切片(阵列)存储在递归中的2D切片(阵列)中
试图通过递归并找到子序列并将子序列切片(数组)在递归中的2D切片(数组)中进行,但在执行后获得NULL 2D切片后,将组合总和问题存储。对于组合总和问题( https://leetcode.com/problems/problems/combination-combination-sum/ )
通过地图,这是可能的
package main
import "fmt"
func main() {
sourceArr := []int{4, 8, 10, 17, 1, 2, 7}
subSeq := make([]int, 0, len(sourceArr))
arrayOfArr := make([][]int, 0)
// i'm calling fuction passing the arguments
FindCombinationV2(sourceArr, subSeq, 10, 0, arrayOfArr)
//after execution i'm getting null array's in 2D array
fmt.Printf("arrayOfArr: %v\n", arrayOfArr)
}
func FindCombinationV2(arr, subSequenceArr []int, target, index int, ans [][]int) {
if index == len(arr) {
if target == 0 {
// i'm getting sub sequences of actual target sum
// here i'm appending subSequence slice in ans 2D slice
ans = append(ans, [][]int{subSequenceArr}...)
}
return
}
if target >= arr[index] {
subSequenceArr = append(subSequenceArr, arr[index])
FindCombinationV2(arr, subSequenceArr, target-arr[index], index, ans)
subSequenceArr = subSequenceArr[:len(subSequenceArr)-1]
}
FindCombinationV2(arr, subSequenceArr, target, index+1, ans)
}
Trying to perform combination sum problem through recursion and finding subsequences and storing subsequences slice (array) in 2D slice (array) in recursion but after execution getting null 2D slice. For combination sum problem (https://leetcode.com/problems/combination-sum/)
Through the map it's possible but I wanted to know how we can do same with the help of 2D Slice (array) [][]int
package main
import "fmt"
func main() {
sourceArr := []int{4, 8, 10, 17, 1, 2, 7}
subSeq := make([]int, 0, len(sourceArr))
arrayOfArr := make([][]int, 0)
// i'm calling fuction passing the arguments
FindCombinationV2(sourceArr, subSeq, 10, 0, arrayOfArr)
//after execution i'm getting null array's in 2D array
fmt.Printf("arrayOfArr: %v\n", arrayOfArr)
}
func FindCombinationV2(arr, subSequenceArr []int, target, index int, ans [][]int) {
if index == len(arr) {
if target == 0 {
// i'm getting sub sequences of actual target sum
// here i'm appending subSequence slice in ans 2D slice
ans = append(ans, [][]int{subSequenceArr}...)
}
return
}
if target >= arr[index] {
subSequenceArr = append(subSequenceArr, arr[index])
FindCombinationV2(arr, subSequenceArr, target-arr[index], index, ans)
subSequenceArr = subSequenceArr[:len(subSequenceArr)-1]
}
FindCombinationV2(arr, subSequenceArr, target, index+1, ans)
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论