@@ -106,10 +106,10 @@ func combinationSumMy(candidates []int, target int) (res [][]int) {
106106// 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
107107func combinationSum (candidates []int , target int ) [][]int {
108108 sort .Ints (candidates )
109- return dfs (candidates , target )
109+ return dfs (candidates , target , [] int {} )
110110}
111111
112- func dfs (candidates []int , target int ) [][]int {
112+ func dfs1 (candidates []int , target int ) [][]int {
113113 ret := [][]int {}
114114 for i , d := range candidates {
115115 if target - d < 0 {
@@ -118,7 +118,24 @@ func dfs(candidates []int, target int) [][]int {
118118 ret = append (ret , []int {d })
119119 continue
120120 }
121- for _ , v := range dfs (candidates [i :], target - d ) {
121+ for _ , v := range dfs1 (candidates [i :], target - d ) {
122+ ret = append (ret , append ([]int {d }, v ... ))
123+ }
124+ }
125+ return ret
126+ }
127+
128+ func dfs (candidates []int , target int , path []int ) [][]int {
129+ ret := [][]int {}
130+ for i , d := range candidates {
131+ if target - d < 0 {
132+ break
133+ } else if target - d == 0 {
134+ path = append (path , d )
135+ ret = append (ret , path )
136+ continue
137+ }
138+ for _ , v := range dfs (candidates [i :], target - d , path ) {
122139 ret = append (ret , append ([]int {d }, v ... ))
123140 }
124141 }
0 commit comments