78. Subsets.go

作者: AnakinSun | 来源:发表于2019-03-26 12:11 被阅读5次

    combination:
    这个是典型的combination做法
    dfs,注意中间结果一定要copy到新的变量中,不然会得到空值

    var ans [][]int
    
    func subsets(nums []int) [][]int {
        ans = [][]int{}
        cur := []int{}
        for i := 0; i <= len(nums); i++ {
            dfs(nums, i, 0, cur)
        }
        return ans
    }
    func dfs(nums []int, n, s int, cur []int) {
        if len(cur) == n {
    //这里一定要拷贝
            tmp := make([]int, n)
            copy(tmp, cur)
            ans = append(ans, tmp)
            return
        }
        for i := s; i < len(nums); i++ {
            cur = append(cur, nums[i])
            dfs(nums, n, i+1, cur)
            cur = cur[:len(cur)-1]
        }
    }
    

    相关文章

      网友评论

        本文标题:78. Subsets.go

        本文链接:https://www.haomeiwen.com/subject/iulgvqtx.html