funcsubsets(nums []int)[][]int{
ret, n, l :=[][]int{{}},len(nums),0for i :=0; i < n; i++{
l =len(ret)// 对于现有结果,复制一份,新的一份追加nums[i]for j :=0; j < l; j++{// 注意复制方法,必须使用中间切片
sub :=make([]int,len(ret[j]))copy(sub, ret[j])
ret =append(ret,append(sub, nums[i]))}}return ret
}
递归枚举
funcsubsets(nums []int)[][]int{returnrecursion(nums,[][]int{{}})}funcrecursion(nums []int, ret [][]int)[][]int{
n,l :=len(nums),len(ret)if n ==0{return ret
}for i:=0;i<l;i++{
sub :=make([]int,len(ret[i]))copy(sub,ret[i])
ret =append(ret,append(sub,nums[0]))}returnrecursion(nums[1:],ret)}
位运算枚举
funcsubsets(nums []int)[][]int{
ret, n :=[][]int{},len(nums)// n个数,循环2的n次方,二进制向量长度为nfor i :=0; i <(1<<n); i++{
sub :=[]int{}// 遍历数组numsfor j :=0; j < n; j++{// 二进制向量从从左往右数第j位为1(表示选第j个数)if((i >> j)&1)==1{
sub =append(sub,nums[j])}}
ret =append(ret,sub)}return ret
}
解法二:回溯
funcsubsets(nums []int)[][]int{returnbacktrack(nums,[]int{},[][]int{{}})}funcbacktrack(nums, sub []int, ret [][]int)[][]int{// 遍历剩余数组,隐含终止条件if len(nums)==0{return ret}for i :=0; i <len(nums); i++{// 如果和前一个数相同就直接放弃if i !=0&& nums[i]== nums[i-1]{continue}// 子数组追加当前这个数
sub =append(sub, nums[i])// 将子数组放到ret中,注意复制方法
tmp :=make([]int,len(sub))copy(tmp, sub)// 本层处理完了,继续下探
ret =backtrack(nums[i+1:], sub,append(ret, tmp))// 下探结束后,恢复初始状态,继续下一次循环// 每次循环的sub都是一样的,ret在不断追加
sub = sub[:len(sub)-1]}return ret
}
leetcode 78. 子集解法一:枚举循环枚举func subsets(nums []int) [][]int { ret, n, l := [][]int{{}}, len(nums),0 for i := 0; i < n; i++ { l = len(ret) // 对于现有结果,复制一份,新的一份追加nums[i] for j := 0; j < ...