LeetCode 39 组合总和 dfs

// 我以为有啥好方法,结果...都是dfs暴力



class Solution {
    public List<List<Integer>> combinationSum(int[] condidates, int target){
        List<List<Integer>> res = new ArrayList<>();
        List<Integer> ans = new ArrayList<>();
        Arrays.sort(condidates);
        dfs(res, ans, condidates, 0, target);
        return res;
    }

    void dfs(List<List<Integer>> res, List<Integer> ans, int[] condidates, int index, int target){
        if (target < 0) return ;
        
        if (target == 0){
            res.add(ans);
            return ;
        }

        for (int i = index;i < condidates.length; i ++){  
            List<Integer> tmp = new ArrayList<>(ans);
            tmp.add(condidates[i]);
            dfs(res, tmp, condidates, i, target - condidates[i]);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/TIMELIMITE/article/details/89889857
今日推荐