Share my golang dfs solution


  • 0
    L

    i do not like that dfs has too many parameters, because it makes dfs difficult to understand. so i define res and tmp out functions.

    var res [][]int
    var tmp []int
    
    func combinationSum(candidates []int, target int) [][]int {
        res = [][]int{}
        tmp = []int{}
    	sort.Ints(candidates)
    	dfs(candidates, target, 0)
    	return res
    }
    
    func dfs(nums []int, target, index int) {
    
    	if target == 0 {
    		now := make([]int,len(tmp))
            copy(now,tmp)
    		res = append(res, now)
    		return
    	}
    	if target < 0 {
    		return
    	}
    	for i := index; i < len(nums); i++ {
    		if target < nums[i] {
    			break
    		}
    		tmp = append(tmp, nums[i])
    		dfs(nums, target-nums[i], i)
    		tmp = tmp[:len(tmp)-1]
    	}
    	return
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.