zoukankan      html  css  js  c++  java
  • Combination Sum

    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.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    For example, given candidate set [2, 3, 6, 7] and target 7,
    A solution set is:

    [
      [7],
      [2, 2, 3]
    ]
    解题思路:深度遍历,找出所有合格的数据。
    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            List<List<Integer>> res=new ArrayList<List<Integer>>();
            Arrays.sort(candidates);
            work(target,0,candidates,res,new ArrayList<Integer>());
            return res;
        }
        //胜读遍历,找出合格的数据
        /*
         * target:代表目标数据
         * index:代表循环的其实位置,也就是查找合格数据的额起始位置
         * candidates 候选值数组
         * res:返回值
         * arrayList:保存一组合格数据的变量
         * */
        public void work(int target, int index, int[] candidates, List<List<Integer>> res, ArrayList<Integer> arrayList){
            //for循环,每次从index出发,因为数组已经排序,所以不会出现重复的数据
            //终止条件为索引越界&&目标值要大于等于当前要检查的候选值
            for(int i=index;i<candidates.length&&candidates[i]<=target;i++){
                /*
                 * 如果target大于当前从candidate中提取的值时,则可以将其加入到arrayList中,在进入深度的遍历查找合格数据
                 * 注意的是,当无论是查找成功还是失败的时候,都要将arrayList的最后一个数据弹出,一遍进行下一次的深度遍历
                 * */
                if(candidates[i]<target){
                    arrayList.add(candidates[i]);
                    work(target-candidates[i], i, candidates, res, arrayList);
                    arrayList.remove(arrayList.size()-1);
                }
                /*
                 * 如果target==当前提取的candidate中的值,则表明查找成功,将这一数组添加到res横中
                 * 并且弹出弹出arrayList中的最后一个数据进行下一次的遍历
                 * */
                else if(candidates[i]==target){
                    arrayList.add(candidates[i]);
                    res.add(new ArrayList<Integer>(arrayList));
                    arrayList.remove(arrayList.size()-1);
                }
            }
        }
    }
    View Code
  • 相关阅读:
    Git 历史/术语/命令/基本操作
    SQL 术语/语法/基本操作-必知必会
    bootstrap cdn地址
    IDEA 快捷键 大幅提高工作效率
    Django3 模版配置/过滤器/markdown=9
    Django3 路由文件位置/文件格式/路由传值=8
    Django3 创建项目/app全流程=7
    VS Code Django解决不必要报错
    Django3 如何使用静态文件/如何自定义后台管理页面=6
    Django3 如何编写单元测试和全面测试=5
  • 原文地址:https://www.cnblogs.com/lichao-normal/p/6250166.html
Copyright © 2011-2022 走看看