zoukankan      html  css  js  c++  java
  • lintcode:数字组合I

    数字组合I

    给出一组候选数字(C)和目标数字(T),找到C中所有的组合,使找出的数字和为T。C中的数字可以无限制重复被选取。

    例如,给出候选数组[2,3,6,7]和目标数字7,所求的解为:

    [7],

    [2,2,3]

     注意事项
    • 所有的数字(包括目标数字)均为正整数。
    • 元素组合(a1, a2, … , ak)必须是非降序(ie, a1 ≤ a2 ≤ … ≤ ak)。
    • 解集不能包含重复的组合。 
    样例

    给出候选数组[2,3,6,7]和目标数字7

    返回 [[7],[2,2,3]]

     解题

    由于输出是要非降序的,先对数组排序,下面DFS的思想解题

    当target =0 的时候需要新建一个ArrayList,再加入的result中,这样是一个新的对象,否则的话,后面的操作可能更新了list

    public class Solution {
        /**
         * @param candidates: A list of integers
         * @param target:An integer
         * @return: A list of lists of integers
         */
        public List<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
            // write your code here
            List<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>();
            int start = 0;
            Arrays.sort(candidates);
            ArrayList<Integer> list = new ArrayList<Integer>();
            DFS(result,list,candidates,target,start);
            return result;
        }
        public void DFS(List<ArrayList<Integer>> result,ArrayList<Integer> list,int[] candidates,int target,int start){
    
            if(target == 0){
                ArrayList<Integer> tmp = new ArrayList<Integer>(list);
               if(!result.contains(tmp))
                    result.add(tmp);
                // result.add(list); 这样加入不成功,不明白
                return;
            }
            for(int i = start;i< candidates.length;i++){
                if(target < candidates[i]  )
                    return;
                target -= candidates[i];
                list.add(candidates[i]);
                DFS(result,list,candidates,target,i);// 从i 开始 说明 可以重复选取
                target += candidates[i];// 恢复上一次的值
                list.remove(list.size() - 1);//恢复上一次的值
            }
        }
    }
  • 相关阅读:
    Codeforces467C George and Job
    Codeforces205E Little Elephant and Furik and RubikLittle Elephant and Furik and Rubik
    Codeforce205C Little Elephant and Interval
    51nod1829 函数
    51nod1574 排列转换
    nowcoder35B 小AA的数列
    Codeforce893E Counting Arrays
    gym101612 Consonant Fencity
    CodeForces559C Gerald and Giant Chess
    CodeForces456D A Lot of Games
  • 原文地址:https://www.cnblogs.com/bbbblog/p/5349289.html
Copyright © 2011-2022 走看看