diff --git a/problems/0046.全排列.md b/problems/0046.全排列.md index 805bc457..c437f7ca 100644 --- a/problems/0046.全排列.md +++ b/problems/0046.全排列.md @@ -275,29 +275,34 @@ class Solution: ### Go ```Go -var res [][]int +var ( + res [][]int + path []int + st []bool // state的缩写 +) func permute(nums []int) [][]int { - res = [][]int{} - backTrack(nums,len(nums),[]int{}) - return res -} -func backTrack(nums []int,numsLen int,path []int) { - if len(nums)==0{ - p:=make([]int,len(path)) - copy(p,path) - res = append(res,p) - } - for i:=0;i List[List[int]]: res = [] @@ -291,7 +291,7 @@ class Solution: ``` 使用used数组 -```python3 +```python class Solution: def subsetsWithDup(self, nums: List[int]) -> List[List[int]]: result = [] @@ -315,26 +315,30 @@ class Solution: ### Go ```Go -var res[][]int -func subsetsWithDup(nums []int)[][]int { - res=make([][]int,0) - sort.Ints(nums) - dfs([]int{},nums,0) - return res +var ( + path []int + res [][]int +) +func subsetsWithDup(nums []int) [][]int { + path, res = make([]int, 0, len(nums)), make([][]int, 0) + sort.Ints(nums) + dfs(nums, 0) + return res } -func dfs(temp, num []int, start int) { - tmp:=make([]int,len(temp)) - copy(tmp,temp) - res=append(res,tmp) - for i:=start;istart&&num[i]==num[i-1]{ - continue - } - temp=append(temp,num[i]) - dfs(temp,num,i+1) - temp=temp[:len(temp)-1] - } +func dfs(nums []int, start int) { + tmp := make([]int, len(path)) + copy(tmp, path) + res = append(res, tmp) + + for i := start; i < len(nums); i++ { + if i != start && nums[i] == nums[i-1] { + continue + } + path = append(path, nums[i]) + dfs(nums, i+1) + path = path[:len(path)-1] + } } ``` diff --git a/problems/0491.递增子序列.md b/problems/0491.递增子序列.md index e33a049d..c0196973 100644 --- a/problems/0491.递增子序列.md +++ b/problems/0491.递增子序列.md @@ -37,7 +37,7 @@ 在[90.子集II](https://programmercarl.com/0090.子集II.html)中我们是通过排序,再加一个标记数组来达到去重的目的。 -而本题求自增子序列,是不能对原数组经行排序的,排完序的数组都是自增子序列了。 +而本题求自增子序列,是不能对原数组进行排序的,排完序的数组都是自增子序列了。 **所以不能使用之前的去重逻辑!** @@ -78,7 +78,7 @@ if (path.size() > 1) { * 单层搜索逻辑 ![491. 递增子序列1](https://img-blog.csdnimg.cn/20201124200229824.png) -在图中可以看出,**同一父节点下的同层上使用过的元素就不能在使用了** +在图中可以看出,**同一父节点下的同层上使用过的元素就不能再使用了** 那么单层搜索代码如下: @@ -340,30 +340,33 @@ class Solution: ``` ### Go -```golang +```go +var ( + res [][]int + path []int +) func findSubsequences(nums []int) [][]int { - var subRes []int - var res [][]int - backTring(0,nums,subRes,&res) + res, path = make([][]int, 0), make([]int, 0, len(nums)) + dfs(nums, 0) return res } -func backTring(startIndex int,nums,subRes []int,res *[][]int){ - if len(subRes)>1{ - tmp:=make([]int,len(subRes)) - copy(tmp,subRes) - *res=append(*res,tmp) +func dfs(nums []int, start int) { + if len(path) >= 2 { + tmp := make([]int, len(path)) + copy(tmp, path) + res = append(res, tmp) } - history:=[201]int{}//记录本层元素使用记录 - for i:=startIndex;i0&&nums[i]= path[len(path)-1] { + path = append(path, nums[i]) + used[nums[i]] = true + dfs(nums, i+1) + path = path[:len(path)-1] + } } } ```