添加 0040.组合总和II.md 中的Java与Go的不使用标记数组的解法

This commit is contained in:
Kai Dang
2021-12-31 17:04:46 +08:00
parent 76df79a8c9
commit d58fe4ea60

View File

@ -255,6 +255,7 @@ public:
## Java
**使用标记数组**
```Java
class Solution {
List<List<Integer>> lists = new ArrayList<>();
@ -292,6 +293,44 @@ class Solution {
}
}
```
**不使用标记数组**
```Java
class Solution {
List<List<Integer>> res = new ArrayList<>();
LinkedList<Integer> path = new LinkedList<>();
int sum = 0;
public List<List<Integer>> combinationSum2( int[] candidates, int target ) {
//为了将重复的数字都放到一起,所以先进行排序
Arrays.sort( candidates );
backTracking( candidates, target, 0 );
return res;
}
private void backTracking( int[] candidates, int target, int start ) {
if ( sum == target ) {
res.add( new ArrayList<>( path ) );
return;
}
for ( int i = start; i < candidates.length && sum + candidates[i] <= target; i++ ) {
//正确剔除重复解的办法
//跳过同一树层使用过的元素
if ( i > start && candidates[i] == candidates[i - 1] ) {
continue;
}
sum += candidates[i];
path.add( candidates[i] );
// i+1 代表当前组内元素只选取一次
backTracking( candidates, target, i + 1 );
int temp = path.getLast();
sum -= temp;
path.removeLast();
}
}
}
```
## Python
**回溯+巧妙去重(省去使用used**
@ -384,6 +423,7 @@ class Solution:
## Go
主要在于如何在回溯中去重
**使用used数组**
```go
func combinationSum2(candidates []int, target int) [][]int {
var trcak []int
@ -423,7 +463,41 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,
}
}
```
**不使用used数组**
```go
func combinationSum2(candidates []int, target int) [][]int {
var trcak []int
var res [][]int
sort.Ints(candidates)
backtracking(0,0,target,candidates,trcak,&res)
return res
}
func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int){
//终止条件
if sum==target{
tmp:=make([]int,len(trcak))
//拷贝
copy(tmp,trcak)
//放入结果集
*res=append(*res,tmp)
return
}
//回溯
for i:=startIndex;i<len(candidates) && sum+candidates[i]<=target;i++{
// 若当前树层有使用过相同的元素,则跳过
if i>startIndex&&candidates[i]==candidates[i-1]{
continue
}
//更新路径集合和sum
trcak=append(trcak,candidates[i])
sum+=candidates[i]
backtracking(i+1,sum,target,candidates,trcak,res)
//回溯
trcak=trcak[:len(trcak)-1]
sum-=candidates[i]
}
}
```
## javaScript
```js