Easy java solution


  • 0
    I
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> ans = new ArrayList<>();
            List<Integer> cur = new ArrayList<>();
            recursive(cur, ans, candidates, 0, target);
            return ans;
        }
        
        public void recursive(List<Integer> cur, List<List<Integer>> ans, int[] candidates, int pos, int target) {
            if(pos >= candidates.length || target < 0) return;
            if(target == 0) {
                ans.add(new ArrayList(cur));
                return;
            }
            cur.add(candidates[pos]);
            recursive(cur, ans, candidates, pos, target - candidates[pos]);
            cur.remove(cur.size()-1);
            recursive(cur, ans, candidates, pos + 1, target);
        }
    }
    

Log in to reply
 

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