1
1
2
-
3
2
import java .util .ArrayList ;
4
3
import java .util .Arrays ;
5
4
11
10
*
12
11
* Note:
13
12
*
14
- * All numbers (including target) will be positive integers.
13
+ * All numbers (including target) will be positive integers.
15
14
*
16
- * Elements in a combination (a1, a2, ... , ak) must be in non-descending order. (ie, a1 <= a2 <= ... <= ak).
15
+ * Elements in a combination (a1, a2, ... , ak) must be in non-descending order.
16
+ * (ie, a1 <= a2 <= ... <= ak).
17
17
*
18
- * The solution set must not contain duplicate combinations.
19
- * For example, given candidate set 2,3,6,7 and target 7, A solution set is:
20
- * [7]
21
- * [2, 2, 3]
18
+ * The solution set must not contain duplicate combinations. For example, given
19
+ * candidate set 2,3,6,7 and target 7, A solution set is: [7] [2, 2, 3]
22
20
*/
23
21
24
22
public class CombinationSum {
@@ -38,20 +36,12 @@ private void combinationSum(int[] candidates, int start, int sum,
38
36
ret .add (new ArrayList <Integer >(solution ));
39
37
return ;
40
38
}
41
- if (start > candidates . length - 1 )
39
+ if (sum > target )
42
40
return ;
43
- int times = 0 ;
44
- while (true ) {
45
- if (sum > target ) {
46
- for (int h = 0 ; h < times ; h ++) {
47
- solution .remove (solution .size () - 1 );
48
- }
49
- break ;
50
- }
51
- combinationSum (candidates , start + 1 , sum , target , ret , solution );
52
- sum += candidates [start ];
53
- solution .add (candidates [start ]);
54
- times ++;
41
+ for (int i = start ; i < candidates .length ; i ++) {
42
+ solution .add (candidates [i ]);
43
+ combinationSum (candidates , start , sum + candidates [i ], target , ret , solution );
44
+ solution .remove (solution .size () - 1 );
55
45
}
56
46
}
57
47
}
0 commit comments