Combination Sum I II之回溯解法

题目

题目I

Given a set of candidate numbers (C) (without duplicates) and a target number (T),
find all unique combinations in C where the candidate numbers sums to T.
The same repeated number may be chosen from C unlimited number of times.

题目II

Given a collection of candidate numbers (C) and a target number (T), 
find all unique combinations in C where the candidate numbers sums to T.
Each number in C may only be used once in the combination.

分析

题目I是在一个没有重复数字,但是数字可以重复选择的数组中找到所有累加和为target的集合,集合中不考虑位置且结果不能有重复。
题目II是在一个有重复数字,但是每个数字只能选择一次的数组中找到所有累加和为target的集合,集合中不考虑位置且结果不能有重复。
还有一种动态规划解法,这里先用回溯。

代码

I

public List<List<Integer>> combinationSum(int[] candidates, int target) {
    List<List<Integer>> res = new ArrayList();
    combinationSum(candidates, target, new ArrayList(), res, 0);
    return res;
}

private void combinationSum(int[] candidates, int target, List<Integer> list, List<List<Integer>> res, int start){
    if(target > 0){
        for(int i = start; i < candidates.length; ++i){
            list.add(candidates[i]);
            //回溯还是从i开始,因为可以重复选取。
            combinationSum(candidates, target - candidates[i],  list, res, i);
            list.remove(list.size() - 1);
        }
    }else if(target == 0){
        res.add(new ArrayList(list));
    }
}

II

public List<List<Integer>> combinationSum2(int[] candidates, int target) {
    Arrays.sort(candidates);    //先排序
    List<List<Integer>> res = new ArrayList();
    if(candidates == null || candidates.length == 0 || target <= 0) return res;
    helper(candidates, res, new ArrayList(), target, 0);
    return res;
}

public void helper(int[] candidates, List<List<Integer>> res, List<Integer> list, int target, int start){
    if(target == 0){
        res.add(new ArrayList(list));
    }else if(target > 0){
        for(int i = start; i < candidates.length; ++i){
            if(i > start && candidates[i] == candidates[i-1]){  //防止重复,I不存在这个问题
                continue; 
            }
            
            list.add(candidates[i]);
            helper(candidates, res, list, target - candidates[i], i + 1);//从下一个数开始
            list.remove(list.size() - 1);
        }
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 背景 一年多以前我在知乎上答了有关LeetCode的问题, 分享了一些自己做题目的经验。 张土汪:刷leetcod...
    土汪阅读 12,911评论 0 33
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 11,072评论 0 23
  • 假装心情好的状态去做事情,心情就真会变好。此时的行为模式: 好的行动 -> 好的意识 -> 好的感受 坏心情下的行...
    依然2009阅读 479评论 0 0
  • 多想,田野安个家,临暖而居。 深草丛是你的画室,浅草地是我的书房,于是,就有了一个诗情画意的家。 晨起,阳光为柴,...
    凌洛夕阅读 513评论 0 3
  • 晚上七点,写完日报,上传今天更新的代码。简单的收拾,挤上了回家的地铁,天气慢慢变热了,地铁中的味道也丰富了起来。站...
    名真好取阅读 348评论 0 0

友情链接更多精彩内容