Easy to understand Java solution


  • 0
    A
    public class Solution {
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            solve(candidates, target, result, new ArrayList<Integer>(), 0);
            return result;
        }
        
        public void solve(int[] candidates, int target, List<List<Integer>> solution, List<Integer> curr_sol, int start) {
            //System.out.println(target + " " + curr_sol);
            if (target == 0) {
                List<Integer> copy_sol = new ArrayList<Integer>();
                copy_sol.addAll(curr_sol);
                solution.add(copy_sol);
            }
            else if (target > 0) {
                for (int i = start; i <= candidates.length - 1; i++) {
                    if (candidates[i] > target) break;
                    curr_sol.add(candidates[i]);
                    solve(candidates, target - candidates[i], solution, curr_sol, i + 1);
                    curr_sol.remove(curr_sol.size() - 1);
                    while(i + 1 <= candidates.length - 1 && candidates[i + 1] == candidates[i]) i++;
                }
            }
        }
    }

Log in to reply
 

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