My JAVA DFS Solution


  • 0
    T
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> results = new ArrayList<>();
            List<Integer> combination = new ArrayList<>();
            dfs(candidates, 0, combination, target, results);
            return results;
        }
        public void dfs(int[] candidates, int startindex, List<Integer> combination,int target, List<List<Integer>> results){
            if(target == 0){
                results.add(new ArrayList<Integer>(combination));
                return;
            }
            for(int i=startindex;i<candidates.length;i++){
                if(!(target<candidates[i])){
                    combination.add(candidates[i]);
                    dfs(candidates,i,combination,target-candidates[i],results);
                    combination.remove(combination.size() -1);
                }
    
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.