Skip to content

Commit d58fe4e

Browse files
committed
添加 0040.组合总和II.md 中的Java与Go的不使用标记数组的解法
1 parent 76df79a commit d58fe4e

File tree

1 file changed

+75
-1
lines changed

1 file changed

+75
-1
lines changed

problems/0040.组合总和II.md

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -255,6 +255,7 @@ public:
255255

256256

257257
## Java
258+
**使用标记数组**
258259
```Java
259260
class Solution {
260261
List<List<Integer>> lists = new ArrayList<>();
@@ -292,6 +293,44 @@ class Solution {
292293
}
293294
}
294295
```
296+
**不使用标记数组**
297+
```Java
298+
class Solution {
299+
List<List<Integer>> res = new ArrayList<>();
300+
LinkedList<Integer> path = new LinkedList<>();
301+
int sum = 0;
302+
303+
public List<List<Integer>> combinationSum2( int[] candidates, int target ) {
304+
//为了将重复的数字都放到一起,所以先进行排序
305+
Arrays.sort( candidates );
306+
backTracking( candidates, target, 0 );
307+
return res;
308+
}
309+
310+
private void backTracking( int[] candidates, int target, int start ) {
311+
if ( sum == target ) {
312+
res.add( new ArrayList<>( path ) );
313+
return;
314+
}
315+
for ( int i = start; i < candidates.length && sum + candidates[i] <= target; i++ ) {
316+
//正确剔除重复解的办法
317+
//跳过同一树层使用过的元素
318+
if ( i > start && candidates[i] == candidates[i - 1] ) {
319+
continue;
320+
}
321+
322+
sum += candidates[i];
323+
path.add( candidates[i] );
324+
// i+1 代表当前组内元素只选取一次
325+
backTracking( candidates, target, i + 1 );
326+
327+
int temp = path.getLast();
328+
sum -= temp;
329+
path.removeLast();
330+
}
331+
}
332+
}
333+
```
295334

296335
## Python
297336
**回溯+巧妙去重(省去使用used**
@@ -384,6 +423,7 @@ class Solution:
384423
## Go
385424
主要在于如何在回溯中去重
386425

426+
**使用used数组**
387427
```go
388428
func combinationSum2(candidates []int, target int) [][]int {
389429
var trcak []int
@@ -423,7 +463,41 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,
423463
}
424464
}
425465
```
426-
466+
**不使用used数组**
467+
```go
468+
func combinationSum2(candidates []int, target int) [][]int {
469+
var trcak []int
470+
var res [][]int
471+
sort.Ints(candidates)
472+
backtracking(0,0,target,candidates,trcak,&res)
473+
return res
474+
}
475+
func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int){
476+
//终止条件
477+
if sum==target{
478+
tmp:=make([]int,len(trcak))
479+
//拷贝
480+
copy(tmp,trcak)
481+
//放入结果集
482+
*res=append(*res,tmp)
483+
return
484+
}
485+
//回溯
486+
for i:=startIndex;i<len(candidates) && sum+candidates[i]<=target;i++{
487+
// 若当前树层有使用过相同的元素,则跳过
488+
if i>startIndex&&candidates[i]==candidates[i-1]{
489+
continue
490+
}
491+
//更新路径集合和sum
492+
trcak=append(trcak,candidates[i])
493+
sum+=candidates[i]
494+
backtracking(i+1,sum,target,candidates,trcak,res)
495+
//回溯
496+
trcak=trcak[:len(trcak)-1]
497+
sum-=candidates[i]
498+
}
499+
}
500+
```
427501
## javaScript
428502

429503
```js

0 commit comments

Comments
 (0)