• Combination Sum_DFS


    Given a set of candidate numbers (C) 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.
    • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    • 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] 

    package leetcode2;
    
    import java.util.*;
    
    public class combaniation_sum {
         public static ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
             ArrayList<ArrayList<Integer>> res=new ArrayList<ArrayList<Integer>>();
             ArrayList<Integer> mem=new ArrayList<Integer>();
             Arrays.sort(candidates);      
             dfs(res,mem,0,candidates,target); // dfs模版!!一定要记住!
             return res;
            }
         
         public static void dfs(ArrayList<ArrayList<Integer>> res,ArrayList<Integer> mem, int deep, int[] candidates, int target) {
            // TODO Auto-generated method stub
            if(target<0){
                return;
            }
            if (target==0){
                if(!res.contains(mem)){
                 res.add(new ArrayList<Integer>(mem));         
                }
                }
            for(int i=deep;i<candidates.length;i++){ 
                 mem.add(candidates[i]);
                 int retaget=target-candidates[i];
                 dfs(res,mem,i,candidates,retaget)    ;
                 if(mem.size()>0)
                 mem.remove(mem.size()-1);
            
            }
        }
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
          int[] s={2,3,6,7};
          System.out.println(combinationSum(s,7));
        }
    
    }
  • 相关阅读:
    Linux命令(一)
    数据库SQL学习(一)
    Eclipse
    VsCode支持的markdown语法参考(一)
    常用算法Tricks(一)
    dispose方法的使用
    收藏一个链接
    我还不知道取什么名字
    NioSocket的用法
    随便乱塞塞2~
  • 原文地址:https://www.cnblogs.com/joannacode/p/4392038.html
Copyright © 2020-2023  润新知