ogv

Untitled

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