zoukankan      html  css  js  c++  java
  • 【LeetCode】Combination Sum

    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 (a1a2, … , 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] 

    这个题目跟第二道题目唯一的区别是重开开始递归下层的位置,不是从i+1开始,而是从i开始,这样就满足了一个元素可以出现无限次的条件。

    public class Solution {
        public ArrayList<ArrayList<Integer>> combinationSum(int[] num, int target) {
            if(num.length==0)
                return re;
            ArrayList<Integer> al = new ArrayList<Integer>();
            Arrays.sort(num);
            FindPath(num,al,target,0,num.length-1);
            re.addAll(remap.keySet());
            return re;
            
        }
        public  Map<ArrayList<Integer>,Integer> remap = new HashMap<ArrayList<Integer>,Integer>();
        public ArrayList<ArrayList<Integer>> re = new ArrayList<ArrayList<Integer>>();
       private void FindPath(int[] num, ArrayList<Integer> al, int target, int start, int end) {
            
            if(start>end)
                return;
            for(int i=start;i<=end;i++){
                al.add(num[i]);
                int temp = sum(al);
                if(temp==target){
                    ArrayList<Integer> at = new ArrayList<Integer>();
                    for(int j=0;j<al.size();j++){
                        at.add(al.get(j));
                    }
                    remap.put(at, 1);
                    al.remove(al.size()-1);
                    return;
                }
                if(temp<target){
                    FindPath(num,al,target,i,end);
                    al.remove(al.size()-1);
                    
                }else{
                    al.remove(al.size()-1);
                    return;
                }
                
            }
        }
       private int sum(ArrayList<Integer> al) {
            int re=0;
            for(int i=0;i<al.size();i++){
                re+=al.get(i);
            }
            return re;
        }
    }
  • 相关阅读:
    JQuery缓冲加载图片插件lazyload.js的使用方法
    CSS3阴影 box-shadow的使用和技巧总结
    HTML符号大全
    TouchSlide
    响应式图片的3种解决方案
    ECMAScript arguments 对象
    call() 方法 和 apply()方法详解
    字体图标 iconfont cssfont
    响应式样式
    1-微信小程序创建项目
  • 原文地址:https://www.cnblogs.com/yixianyixian/p/3746525.html
Copyright © 2011-2022 走看看