Help: Runtime Error Message: Line 16: java.lang.StackOverflowError


  • 0
    L

    Runtime Error Message: Line 16: java.lang.StackOverflowError
    Last executed input: [92,71,89,74,102,91,70,119,86,116,114,106,80,81,115,99,117,93,76,77,111,110,75,104,95,112,94,73], 310
    Line 16 : list.add(candidates[k]);
    Who can help me to go out of this problems?
    Thanks a lot.

     public List<List<Integer>> combinationSum(int[] candidates, int target) {
    	List<List<Integer>>  rtn = new ArrayList<List<Integer>>();
    	int k=0,tmp=0;
    	int[] count = new int[candidates.length];
    	trackback(candidates, count, k, tmp, target, rtn, new ArrayList<Integer>());
    	return rtn;
    }
    
    void trackback(int[] candidates, int[] count, int k, int currentSum, int target, List<List<Integer>>  rtn, List<Integer> list){
    	while(k<candidates.length && currentSum <= target){
    		if(currentSum+candidates[k]>target){
    			k++;
    			continue;
    		}
    		list.add(candidates[k]);
    		currentSum += candidates[k];
    		count[k]++;
    	}
    	k--;
    	if(currentSum == target){
    		rtn.add(new ArrayList<Integer>(list));
    	}
    	//backtrack
    	while(k>0 && count[k]==0){
    		k--;
    	}
    	if(k>=0 && count[k]>0){
    		count[k]--;
    		currentSum -= candidates[k];
    		list.remove(list.size()-1);
    		k++;
    	}
    	if(k==0){
    		return;
    	}else{
    		trackback(candidates,count,k,currentSum,target,rtn,list);
    	}
    }

  • 0
    Q

    Do you know how to use a debugger? If not you should learn.


  • 0
    L

    Thanks for your answer, i have solved this problems.Recursion is so many that leads to stack overflow.


Log in to reply
 

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