39. 组合总和

回溯

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

class Solution {

    List<List<Integer>> list = new ArrayList<>();
    LinkedList<Integer> li = new LinkedList<>();

    public List<List<Integer>> combinationSum(int[] candidates, int target) {

        backtracking(candidates, target, 0);

        return list;
    }

    public void backtracking(int[] candidates, int target, int startIndex){

        /**
         * 终止条件
         * 如果target == 0,说明刚好找到解
         * 如果target < 0,说明剩下的数字和已经大于target了,就不用再继续搜索了
         */
        if (target == 0){

            list.add(new ArrayList<>(li));
            return;
        }

        if (target < 0){
            return;
        }

        /**
         * 递归条件中,startIndex从i而不是i + 1开始,因为每个数字可重复使用
         */
        for (int i = startIndex; i < candidates.length; i++) {

            li.add(candidates[i]);
            backtracking(candidates, target - candidates[i], i);
            li.removeLast();
        }
    }
}

/**
 * 时间复杂度 O(n×2^n)
 * 空间复杂度 O(target)
 */

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

posted @ 2022-01-11 16:16  振袖秋枫问红叶  阅读(37)  评论(0)    收藏  举报