Created
February 16, 2021 12:47
-
-
Save anil477/012bced56d35d7cd048452d3322cfb5a to your computer and use it in GitHub Desktop.
Given an array of distinct integers candidates and a target integer target, return a list of all unique combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// https://leetcode.com/problems/combination-sum/ | |
class Solution { | |
public List<List<Integer>> combinationSum(int[] candidates, int target) { | |
Arrays.sort(candidates); | |
List<List<Integer>> result = new ArrayList<List<Integer>>(); | |
getResult(result, new ArrayList<Integer>(), candidates, target, 0); | |
return result; | |
} | |
private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start) { | |
// System.out.println(cur); | |
if (target > 0) { | |
for (int i = start; i < candidates.length && candidates[i] <= target; i++) { | |
cur.add(candidates[i]); | |
getResult(result, cur, candidates, target - candidates[i], i); | |
cur.remove(cur.size() - 1); | |
} | |
} else if(target == 0 ){ | |
result.add(new ArrayList<Integer>(cur)); | |
} | |
} | |
} |
Author
anil477
commented
Feb 16, 2021
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment