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);
        }
    }


  • 相关阅读:
    前后端分离下的自动化部署
    bouncy castle的配置
    列出本机JCE提供者,支持消息摘要算法,支持公钥私钥算法
    javaScript动态参数
    PKCS10生成证书csr
    未来编程语言---猜测
    html编辑网站
    java反编译工具JD-GUI
    java.lang.OutOfMemoryError: PermGen space
    修改idea的运行内存
  • 原文地址:https://www.cnblogs.com/whatyouknow123/p/7497155.html
Copyright © 2011-2022 走看看