• LeetCode


    题目:

    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.
    • Elements in a combination (a1, a2, … , ak) must be in non-descending order. (ie, a1a2 ≤ … ≤ ak).
    • 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]

    思路:

    每个数字只能出现一次了,所以递归时直接定位到下一个元素。

    package sum;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    public class CombinationSumII {
    
        public List<List<Integer>> combinationSum2(int[] candidates, int target) {
            Arrays.sort(candidates);
            List<List<Integer>> res = new ArrayList<List<Integer>>();
            List<Integer> record = new ArrayList<Integer>();
            combine(candidates, 0, candidates.length, res, record, target);
            return res;
        }
        
        private void combine(int[] nums, int start, int end, List<List<Integer>> res, List<Integer> record, int target) {
            for (int i = start; i < end; ++i) {
                List<Integer> newRecord = new ArrayList<Integer>(record);
                newRecord.add(nums[i]);
                int sum = sum(newRecord);
                int rem = target - sum;
                if (rem == 0) {
                    res.add(newRecord);
                } else if (rem > 0 && rem >= nums[i]) {
                    combine(nums, i + 1, end, res, newRecord, target);
                } else if (rem < 0) {
                    break;
                }
                
                while (i + 1 < end && nums[i + 1] == nums[i]) ++i;
            }
        }
        
        private int sum(List<Integer> record) {
            int sum = 0;
            for (int i : record)
                sum += i;
            return sum;
        }
        
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            int[] nums = { 10,1,2,7,6,1,5 };
            CombinationSumII c = new CombinationSumII();
            List<List<Integer>> res = c.combinationSum2(nums, 8);
            for (List<Integer> l : res) {
                for (int i : l)
                    System.out.print(i + "	");
                System.out.println();
            }
        }
    
    }
  • 相关阅读:
    springboot缓存-Ehcache
    springboot+spring data jpa 多数据源配置
    vue+element 上传图片控件
    springboot下载文件
    easyPoi导入带图片的excel
    内外网同时使用(宽带内网无线内网)
    mysql 8.0 安装
    搭建一个Vue前端项目
    mybatis反向代理自动生成mapper文件
    【1】idea Live Templates
  • 原文地址:https://www.cnblogs.com/null00/p/5075511.html
Copyright © 2020-2023  润新知