11
2-
32import java .util .ArrayList ;
43import java .util .Arrays ;
54
1110 *
1211 * Note:
1312 *
14- * All numbers (including target) will be positive integers.
13+ * All numbers (including target) will be positive integers.
1514 *
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).
1717 *
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]
2220 */
2321
2422public class CombinationSum {
@@ -38,20 +36,12 @@ private void combinationSum(int[] candidates, int start, int sum,
3836 ret .add (new ArrayList <Integer >(solution ));
3937 return ;
4038 }
41- if (start > candidates . length - 1 )
39+ if (sum > target )
4240 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 );
5545 }
5646 }
5747}
0 commit comments