Loading

LeetCode 39 组合总数

LeetCode39 组合总数

题目描述

给定一个无重复元素的数组 candidates 和一个目标数 target ,找出 candidates 中所有可以使数字和为 target 的组合。

candidates 中的数字可以无限制重复被选取。

样例

输入:candidates = [2,3,6,7], target = 7,
所求解集为:
[
  [7],
  [2,2,3]
]
输入:candidates = [2,3,5], target = 8,
所求解集为:
[
  [2,2,2,2],
  [2,3,3],
  [3,5]
]

算法分析

暴力搜索

搜索顺序问题

时间复杂度

Java代码

class Solution {
    static List<List<Integer>> ans = new ArrayList<List<Integer>>();

    static void dfs(int[] candidates, int target, int u, int sum, List<Integer> t){
        if(sum > target) return;

        if(u == candidates.length){
            if(sum == target){
                ans.add(new ArrayList<Integer>(t));
            }
            return;
        }

        for(int i = 0; sum + i * candidates[u] <= target; i++){
            dfs(candidates, target, u+1, sum+candidates[u]*i, t);
            t.add(candidates[u]); //
        }

        for(int i = 0; sum + i * candidates[u] <= target; i++){
            t.remove(t.size()-1);
        }
    }

    public List<List<Integer>> combinationSum(int[] candidates, int target) {
        ans.clear();
        List<Integer> t = new ArrayList<Integer>();
        dfs(candidates,target,0,0,t);
        return ans;
    }
}
posted @ 2020-11-03 14:15  想用包子换论文  阅读(50)  评论(0)    收藏  举报