Simple Java Solution


  • 0
    S
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            int len = candidates.length;
            
            List<List<Integer>> result = new LinkedList<List<Integer>>();
            
            addList(result,new LinkedList<Integer>(), candidates, target, 0);
            
            return result;
        }
        
        public void addList (List<List<Integer>> result, List<Integer> cur, int[] candidates, int target, int index) {
            for(int i=index;i<candidates.length;i++) {
                if(candidates[i] < target) {
                    List<Integer> list = new LinkedList<Integer>();
                    list.addAll(cur);
                    list.add(candidates[i]);
                    addList(result, list, candidates, target - candidates[i], i);
                } else if (candidates[i] == target) {
                    List<Integer> list = new LinkedList<Integer>();
                    list.addAll(cur);
                    list.add(candidates[i]);
                    result.add(list);
                } else {
                    break;
                }
            }
        }
    }

Log in to reply
 

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