Java DFS Solution with Comments


  • 0
    Z
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            // use dfs idea to solve this problem
            // n = candidates.length
            // recursion tree has n level
            // each level represents how many candidates[i] we need
            // each level has multiple branches, depends on remain
            // time complexity is O(k^n), k = max(target / candidates[i]);
            List<List<Integer>> res = new ArrayList<>();
            List<Integer> cur = new ArrayList<>();
            dfs(res, cur, candidates, target, 0, 0);
            return res;
        }
        
        private void dfs(List<List<Integer>> res, List<Integer> cur, int[] array, int target, int sum, int index) {
            if (index == array.length) {
                if (sum == target) {
                    res.add(new ArrayList<>(cur));
                }
                return;
            }
            for (int i = 0; i * array[index] <= target - sum; i++) {
                sum += i * array[index];
                for (int j = 0; j < i; j++) {
                    cur.add(array[index]);
                }
                dfs(res, cur, array, target, sum, index + 1);
                sum -= i * array[index];
                for (int j = 0; j < i; j++) {
                    cur.remove(cur.size() - 1);
                }
            }
        }
    }
    

Log in to reply
 

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