Problem 39

Combination Sum

Posted by Ruizhi Ma on July 22, 2019

问题描述

https://leetcode.com/problems/combination-sum/

解决思路

直接看篮子王的视频吧,这里不太好解释,看代码应该也能看个大概懂。

问题解惑

有很多问题,递归如何调用,回溯怎么回溯,一层层回溯的过程。都通过debug理解了,没办法一句句说清楚,这题要多回头看看。

代码

class Solution {
    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        List<List<Integer>> res = new ArrayList<>();
        
        //corner case
        if(candidates.length == 0 || candidates == null || target < 0) return res;
        
        Arrays.sort(candidates);
        helper(res, new ArrayList<>(), candidates, target, 0);
        
        return res;
    }
    
    public void helper(List<List<Integer>> res, List<Integer> list, int[] candidates, int target, int start){
        //backtracking condition
        if(target < 0) return;
        
        //one result has been found and add it into res
        if(target == 0){
            res.add(new ArrayList<>(list));
            return;
        }
        
        for(int i = start; i < candidates.length; i++){
            list.add(candidates[i]);
            helper(res, list, candidates, target - candidates[i], i);//recursive function
            list.remove(list.size() - 1);
        }
    }
}

复杂度分析

  1. 时间复杂度:O(2^n)
  2. 空间复杂度:O(n)