@@ -255,6 +255,7 @@ public:
255
255
256
256
257
257
## Java
258
+ ** 使用标记数组**
258
259
``` Java
259
260
class Solution {
260
261
List<List<Integer > > lists = new ArrayList<> ();
@@ -292,6 +293,44 @@ class Solution {
292
293
}
293
294
}
294
295
```
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
+ ```
295
334
296
335
## Python
297
336
** 回溯+巧妙去重(省去使用used**
@@ -384,6 +423,7 @@ class Solution:
384
423
## Go
385
424
主要在于如何在回溯中去重
386
425
426
+ ** 使用used数组**
387
427
``` go
388
428
func combinationSum2 (candidates []int , target int ) [][]int {
389
429
var trcak []int
@@ -423,7 +463,41 @@ func backtracking(startIndex,sum,target int,candidates,trcak []int,res *[][]int,
423
463
}
424
464
}
425
465
```
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
+ ```
427
501
## javaScript
428
502
429
503
``` js
0 commit comments