zoukankan      html  css  js  c++  java
  • [leetcode]40. Combination Sum II

    和39题不同的地方:
    1.数组中有重复的数

    2.数组中的数只能用一次

    import java.util.*;
    
    /**
     * Created by lvhao on 2017/7/3.
     * Given a collection of candidate numbers (C) and a target number (T),
     * find all unique combinations in C where the candidate numbers sums to T.
    
     Each number in C may only be used once in the combination.
    
     Note:
     All numbers (including target) will be positive integers.
     The solution set must not contain duplicate combinations.
     For example, given candidate set [10, 1, 2, 7, 6, 1, 5] and target 8,
     A solution set is:
     [
     [1, 7],
     [1, 2, 5],
     [2, 6],
     [1, 1, 6]
     ]
     相对于39题,由于每个数只能用一次,所以每次递归时遍历都是从index+1开始,而且由于数组中有重复的数,
     所以
     1.先用一个set去装结果,当set中不含有的时候才装进去,最后转化为list。
     2.加一个判断:当又回溯回来,本层的数要改变的时候,先判断是不是和前边得数相等,相等就continue
        但是怎么判断本次是不是回溯回来的呢:如果i > index,就是。
     第二种方法更好
     */
    public class Q40CombinationSum2 {
        public static void main(String[] args) {
            int[] nums = new int[]{10, 1, 2, 7, 6, 1, 5};
            System.out.println(combinationSum2(nums,8));
        }
        public static List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<List<Integer>> result = new ArrayList<>();
            backTracking(result,candidates,new ArrayList<>(),target,0);
            return new ArrayList<>(result);
        }
        public static void backTracking(List<List<Integer>> result,int[] candidates,
                                        List<Integer> cur,int left,int index)
        {
            if(left == 0)
            {
                List<Integer> temp = new ArrayList<>(cur);
                result.add(temp);
                return;
            }
            for(int i = index;i < candidates.length;i++)
            {
                if(i > index && candidates[i] == candidates[i-1])
                    continue;
                if (candidates[i] <= left)
                {
                    cur.add(candidates[i]);
                    backTracking(result,candidates,cur,left-candidates[i],i+1);
                    cur.remove(cur.size()-1);
                }
                else
                    break;
            }
    
        }
    }
  • 相关阅读:
    About Inside the Azure Storage Outage of November 18th
    Microsoft Azure 的一些限制 Global
    js递归遍历树形json数据,根据关键字查找节点
    如何修改 WordPress 的默认 Gravatar 头像
    flatpickr功能强大的日期时间选择器插件
    express框架,使用 static 访问 public 内静态文件
    nodejs实时的检测系统文件的变化(无需重启服务)
    redis的常用命令
    NPM install -save 和 -save-dev 傻傻分不清
    Git的使用--如何将本地项目上传到Github
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7112383.html
Copyright © 2011-2022 走看看