Output format problem

  • 1
    Input:	[8,7,4,3], 11
    Output:	[[4,4,3],[7,4],[8,3]]
    Expected:	[[3,4,4],[3,8],[4,7]]

    My code:

    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
        return sum(candidates,target,new ArrayList<Integer>(),0);
    public ArrayList<ArrayList<Integer>> sum(int[] test,int target,ArrayList<Integer> list,int index){
        ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
        if( target ==0){
            return result;
        if(target < 0||index == test.length){
        	return result;
        //No taking current node
        result.addAll(sum(test,target,new ArrayList<Integer>(list),index+1));
        //take current node
        return result;

  • 0

    add one line :
    Collections.sort(list); Accepted

    Doesn't figure out why the output format is vital.
    Actually, sort the arraylist before being inserted is not a good idea.
    Anyone has better solution?

  • 0

    Can you algorithm handle duplicates?

  • 0

    I got the same error:
    Input: [8,7,4,3], 11
    Output: [[7,4],[8,3],[4,4,3]]
    Expected: [[3,4,4],[3,8],[4,7]]

    I think the output check needs to be improved.


    update: sort the input vector solved the problem. (which should be done in the output check IMO)

Log in to reply

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