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);//恢复上一次的值
            }
        }
    }
  • 相关阅读:
    python学习:设计一个算法将缺失的数字找出来。
    zabbix如何监控进程
    centos7 网桥的配置
    Zabbix 3.0 监控Web
    一个监控进程的脚本,若进程异常重启进程
    centos 6.8 下安装redmine(缺陷跟踪系统)
    iOS UICollectionView简单使用
    ios开发图片点击放大
    IOS中实现图片点击全屏预览
    iOS 中有用的开源库
  • 原文地址:https://www.cnblogs.com/theskulls/p/5349289.html
Copyright © 2011-2022 走看看