Leetcode: Combination Sum II

This problem is defined as follows: 


Given a collection of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Each number in candidates may only be used once in the combination.

Note: The solution set must not contain duplicate combinations.




Here are some examples pertaining to this LeetCode Question: 

Input: candidates = [10,1,2,7,6,1,5], target = 8 Output: [ [1,1,6], [1,2,5], [1,7], [2,6] ]

Input: candidates = [2,5,2,1,2], target = 5 Output: [ [1,2,2], [5] ]


And the output is as follows: 


class Solution {

    public List < List < Integer >> combinationSum2(int[] candidates, int target) {

        Arrays.sort(candidates); //sort the lesser values to be earlier in this array. 

        List < List < Integer >> res = new ArrayList < List < Integer >> (); //set a ArrayLists of lists to store the paths

        List < Integer > path = new ArrayList < Integer > (); //This is the current burner path

        dfs_com(candidates, 0, target, path, res); //this is the bfs method for the dfs 

        return res;

    }


    public void dfs_com(int[] cand, int cur, int target, List < Integer > path, List < List < Integer >> res) {


        //if there is nothing to add, add the path to the list, and the method is done

        //or call the previous recursive method in the stack. 

        if (target == 0) {

            res.add(new ArrayList(path));

            return;

        }


        //return if there is an invalid result, and remove. 

        if (target < 0) return;


        //iterate through and perform a recursion from the current integer index.

        for (int i = cur; i < cand.length; i++) {

            //make sure that these numbers are not the same. 

            if (i > cur && cand[i] == cand[i - 1]) continue;

            //add the number to the path

            path.add(path.size(), cand[i]);

            //perform bfs, to check if path is valid, and how to find new paths

            dfs_com(cand, i + 1, target - cand[i], path, res);

            //if there is an invalid path or a stack overflow, remove the result. 

            path.remove(path.size() - 1);

        }

    }

}





Comments

Popular Posts