Advertisement
ogv

Untitled

ogv
Aug 19th, 2019
235
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.48 KB | None | 0 0
  1. /*
  2. Runtime: 5 ms, faster than 48.19% of Java online submissions for Combination Sum.
  3. Memory Usage: 36.5 MB, less than 100.00% of Java online submissions for Combination Sum.
  4. */
  5. class Solution {
  6.     public List<List<Integer>> combinationSum(int[] candidates, int target) {
  7.         List<List<Integer>> results = new ArrayList<List<Integer>>();
  8.        
  9.         if (target == 0){
  10.             results.add(new ArrayList<Integer>());
  11.         }
  12.        
  13.         int sum = 0;
  14.         int[] counts = new int[candidates.length];
  15.         int currentLead = 0;
  16.        
  17.         while (currentLead < candidates.length) {
  18.             counts[currentLead]++;
  19.            
  20.             sum += candidates[currentLead];
  21.            
  22.             if (sum == target) {
  23.                 List<Integer> currentResult = new ArrayList<Integer>();
  24.                
  25.                 for (int i = 0; i < candidates.length; i++) {
  26.                     for (int j = 0; j < counts[i]; j++) {
  27.                         currentResult.add(candidates[i]);
  28.                     }
  29.                 }
  30.                
  31.                 results.add(currentResult);
  32.             }
  33.            
  34.             if (sum >= target) {                
  35.                 sum -= candidates[currentLead] * counts[currentLead];
  36.                 counts[currentLead] = 0;
  37.                 currentLead++;
  38.             }
  39.             else {
  40.                 currentLead = 0;
  41.             }
  42.         }
  43.        
  44.        
  45.         return results;
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement