• [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;
            }
    
        }
    }
  • 相关阅读:
    在IIS上部署 .Net Core 3.0 项目踩坑实录
    .net core3.0部署Linux服务器 使用Docker容器和Nginx反代理教程
    播放器 AxWindowsMediaPlayer控件的使用
    Github下载慢和下载过程中断等情况的解决方案
    GitHub第一次上传遇到的问题
    DataGridView && 增加复选框(checkbox)方法
    努力
    绘图:drawImage一个用法
    Tuple<T1,T2,.........T> 元组简单使用
    随机的标识符GUID
  • 原文地址:https://www.cnblogs.com/stAr-1/p/7112383.html
Copyright © 2020-2023  润新知