zoukankan      html  css  js  c++  java
  • Combination Sum

    Descirption:

    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]
    ]


    Thoughts:
    要解决这个问题要使用回溯的思想。所谓的回溯就是对所有的解进行枚举,能够走通的就继续走,否则就回退一步,尝试另一条路径,直到所有的路径都进行了遍历。
    对于当前的回溯点我们需要直到当前所有可能的路径,然后朝着所有可能的路径继续前进,对于不可能的路径直接跳过

    以下是java代码package middle;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class CombinationSum {
        
        public List<List<Integer>> combinationSum(int[] candidates, int target){
            List<List<Integer>> list = new ArrayList<List<Integer>>();
            Arrays.sort(candidates);
            backtrack(list, new ArrayList(),candidates,  target, 0);
        /*    System.out.println(list);*/
            return list;
        }
        
        private void backtrack(List<List<Integer>> list, ArrayList arrayList,
                int[] candidates, int target, int start) {
            // TODO Auto-generated method stub
            if(target < 0){
                return;
            }else if(target == 0){

          //we should new an ArrayList, because the arrayList will change later,
          //if we do not copy it's value, list will add []

                list.add(new ArrayList<Integer>(arrayList));
            }else{
                for(int i = start;i<candidates.length;i++){
                    arrayList.add(candidates[i]);
                    backtrack(list, arrayList, candidates, target-candidates[i], i);
                    arrayList.remove(arrayList.size() - 1);
                }
            }
        }
        
        public static void main(String[] args){
            CombinationSum sum = new CombinationSum();
            int[] candidates = new int[]{2, 3,5 ,7};
            sum.combinationSum(candidates, 7);
        }
    }


  • 相关阅读:
    AndroidStudio 混淆打包
    android监听键盘
    Emoji字符检查与替换
    自定义Toast样式-两行文本居中显示
    强密码验证的正则表达式
    图片处理之-Bitmap.Config,jpeg压缩与大小
    Android App开之标注切图
    Android基础之CountDownTimer 倒计时类
    Android Handler Leak
    单目标跟踪CVPR 2018 ECO+
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7497155.html
Copyright © 2011-2022 走看看