【面试题】联合求和

polaris · · 3562 次点击
```go func combinationSum(candidates []int, target int) [][]int { sort.Ints(candidates) record := []int{} resultChan := make(chan [][]int) go forkJoin(candidates, target, record, resultChan) result := <-resultChan result = unique(result) return result } func forkJoin(candidates []int, target int, record []int, resultChan chan [][]int) { result := make([][]int, 0) defer func() { resultChan <- result }() if len(candidates) == 0 { if target == 0 { result = append(result, record) } return } resultChanArr := make([]chan [][]int, 0) for _, v := range candidates { middleTarget := target - v middleIndex := seekIndex(candidates, middleTarget) middleRecord := append(record, v) middleResultChan := make(chan [][]int) resultChanArr = append(resultChanArr, middleResultChan) go forkJoin(candidates[0:middleIndex], middleTarget, middleRecord, middleResultChan) } for _, middleResultChan := range resultChanArr { middleResult := <-middleResultChan if len(middleResult) != 0 { for _, middleResultRow := range middleResult { result = append(result, middleResultRow) } } } } func seekIndex(candidates []int, middleTarget int) int { for i, v := range candidates { if middleTarget < v { return i } } return len(candidates) } func unique(src [][]int) [][]int { tgt := make([][]int, 0) for _, v := range src { ok := true for i := 0; i < len(v)-1; i++ { if v[i] > v[i+1] { ok = false break } } if ok { tgt = append(tgt, v) } } return tgt } ```
#3