博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
leetcode — combination-sum-ii
阅读量:5925 次
发布时间:2019-06-19

本文共 2689 字,大约阅读时间需要 8 分钟。

import java.util.ArrayList;import java.util.Arrays;import java.util.List;/** *Source : https://oj.leetcode.com/problems/combination-sum-ii/ * * Created by lverpeng on 2017/7/14. * * 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, a1 ≤ a2 ≤ … ≤ 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] * */public class CombinationSum2 {    private List
> result = new ArrayList
>(); /** * 先考虑一个数字,比如第一位,其他位以此类推,第一位为例 * * @param num * @param start * @param end * @param target * @param list */ public void combinationSum(int[] num, int start, int end, int target, List
list) { if (target == 0 && list.size() > 0) { Integer[] newList = new Integer[list.size()]; System.arraycopy(list.toArray(new Integer[list.size()]), 0, newList, 0, list.size()); result.add(Arrays.asList(newList)); return; } int index = start; int multiple = 0; while (index <= end && num[index] <= target) { if (index > start && num[index] == num[index-1]) { index ++; continue; } int newTarget = target - num[index]; list.add(num[index]); combinationSum(num, index + 1, end, newTarget, list); list.remove(list.size() - 1); index++; } } public List
> combination(int[] num, int target) { Arrays.sort(num); List
combinationList = new ArrayList
(); combinationSum(num, 0, num.length - 1, target, combinationList); return result; } private static void printMatrix(List
> list) { StringBuilder stringBuilder = new StringBuilder(); for (List
intList : list) { for (Integer num : intList) { stringBuilder.append(num); stringBuilder.append(", "); } stringBuilder.delete(stringBuilder.length() - 2, stringBuilder.length() - 1); stringBuilder.append("\n"); } System.out.println(stringBuilder); } public static void main(String[] args) { CombinationSum2 combinationSum = new CombinationSum2(); int[] num = new int[]{10,1,2,7,6,1,5}; printMatrix(combinationSum.combination(num, 8)); }}

转载于:https://www.cnblogs.com/sunshine-2015/p/7461434.html

你可能感兴趣的文章
第23周六
查看>>
分布式Hadoop安装(二)
查看>>
Styles and Themes
查看>>
日期的常规运用
查看>>
pgrep 查询进程的工具
查看>>
OAF_架构MVC系列3 - View的概述(概念)
查看>>
java的定时器用法
查看>>
TempDB--临时表的缓存
查看>>
什么是java 序列化,如何实现java 序列化?
查看>>
Java模式(适配器模式)
查看>>
腾讯开放平台:无法拉起客户端分享的问题
查看>>
因你常说没关系,他便不觉对不起。
查看>>
Android 4.4 KitKat升级率已经接近18%(2014-07-09 07:29)
查看>>
Python list去重及找出,统计重复项
查看>>
C#Light 再推荐,顺便介绍WP8 功能展示项目
查看>>
查询所有数据库,数据集
查看>>
[转]虚拟现实和现实增强技术带来的威胁
查看>>
lua 按拉分析与合成
查看>>
借蜡烛
查看>>
Android中的UriMatcher、ContentUrist和ContentResolver
查看>>