Java simple backtracking method


  • 0
    H
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
             List<List<Integer>> ans = new ArrayList<>();
             combination(ans, new ArrayList<Integer>(),candidates, target, 0);
             return ans;
            
        }
        
        
    private void combination(List<List<Integer>> ans, List<Integer> comb,int[] candidates, int k,  int start) {
    	if(k<0) return;
    	else if ( k == 0) {
    		List<Integer> li = new ArrayList<Integer>(comb);
    		ans.add(li);
    		return;
    	}
    	else{
    	for (int i = start; i <candidates.length; i++) {
    		comb.add(candidates[i]);
    		combination(ans, comb,candidates, k-candidates[i], i);
    		comb.remove(comb.size() - 1);
    	}
    	}
    }
    }
    

Log in to reply
 

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