leetcode 78. 子集 golang實現

描述
給定一組不含重複元素的整數數組nums,返回該數組所有可能的子集(冪集)。

說明:解集不能包含重複的子集。

示例:

輸入: nums = [1,2,3]
輸出:
[
 [3],
 [1],
 [2],
 [1,2,3],
 [1,3],
 [2,3],
 [1,2],
 []
]
思路
回溯
要注意排序的問題 不然會有重複子集 如:[2,3] [3,2]
pre 爲 路徑中上一個邊 保證當前邊 > pre即可 
實現
var IntMax = int(^uint(0) >> 1)
var IntMin = ^IntMax
func subsets(nums []int) [][]int {
	ret := make([][]int, 0)
	if len(nums) == 0{
		return ret
	}

	tmpRet := make([]int, 0)
	ret = subsetsBackTracking(tmpRet, nums, ret)

	return ret
}

func subsetsBackTracking(tmpRet []int, tmpNums []int, ret [][]int)[][]int{
	ret = append(ret, tmpRet)

	var pre = IntMin
	if len(tmpRet) > 0{
		pre = tmpRet[len(tmpRet) - 1]
	}

	for  index, num := range tmpNums{
		if num > pre{
			newRet := make([]int, 0)
			newRet = append(newRet, tmpRet...)
			newRet = append(newRet, num)

			newNums := make([]int, 0)
			newNums = append(newNums, tmpNums...)
			newNums = append(newNums[0:index], newNums[index+1:]...)
			ret = subsetsBackTracking(newRet, newNums, ret)

		}
	}

	return ret
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章