shriyanshi24jindal

Combination Sum

Mar 30th, 2026
116
0
Never
Not a member of GistPad yet? Sign Up, it unlocks many cool features!
Java 5.89 KB | None | 0 0
  1. class Solution {
  2. public List<List<Integer>> combinationSum(int[] candidates, int target) {
  3. List<List<Integer>> result = new ArrayList<>();
  4. List<Integer> temp = new ArrayList<>();
  5.  
  6. findCombinationSum(candidates, target, 0, result, temp);
  7. return result;
  8. }
  9.  
  10. public void findCombinationSum(int[] nums, int target, int index, List<List<Integer>> result, List<Integer> temp)
  11. {
  12.  
  13. // Base condition 1: when target becomes 0
  14. if(target == 0)
  15. {
  16. result.add(new ArrayList<>(temp));
  17. return;
  18. }
  19.  
  20. // Base condition 2: when we reach end of the array
  21. if(index == nums.length)
  22. return;
  23.  
  24. if(nums[index] <= target)
  25. {
  26. // pick the element
  27. temp.add(nums[index]);
  28. findCombinationSum(nums, target - nums[index], index, result, temp);
  29.  
  30. // do not pick the element
  31. temp.remove(temp.size()-1);
  32. }
  33. findCombinationSum(nums, target, index+1, result, temp);
  34. return;
  35. }
  36. }
RAW Paste Data Copied