博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode - Combination Sum
阅读量:6848 次
发布时间:2019-06-26

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

题目:

Given a set of candidate numbers (C) and a target number (T), find all unique combinations in C where the candidate numbers sums to T.

The same repeated number may be chosen from C unlimited number of times.

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 2,3,6,7 and target 7,

A solution set is:
[7]
[2, 2, 3]

思路:递归,不断地尝试余下的值。

package sum;import java.util.ArrayList;import java.util.Arrays;import java.util.List;public class CombinationSum {    public List
> combinationSum(int[] candidates, int target) { Arrays.sort(candidates); int len = removeDuplicates(candidates); List
> res = new ArrayList
>(); List
record = new ArrayList
(); combine(candidates, 0, len, res, record, target); return res; } private void combine(int[] nums, int start, int end, List
> res, List
record, int target) { for (int i = start; i < end; ++i) { List
newRecord = new ArrayList
(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, end, res, newRecord, target); } else if (rem < 0) { break; } } } private int sum(List
record) { int sum = 0; for (int i : record) sum += i; return sum; } private int removeDuplicates(int[] nums) { int n = nums.length; int j = 0; for (int i = 1; i < n; ++i) { if (nums[i] != nums[i - 1]) { nums[++j] = nums[i]; } } return j + 1; } public static void main(String[] args) { // TODO Auto-generated method stub int[] nums = { 1, 2, 2, 3, 6, 7 }; CombinationSum c = new CombinationSum(); List
> res = c.combinationSum(nums, 7); for (List
l : res) { for (int i : l) System.out.print(i + "\t"); System.out.println(); } }}

 

转载地址:http://ybrul.baihongyu.com/

你可能感兴趣的文章
私有云portal
查看>>
Hadoop-环境搭建
查看>>
远程登录ssh免密码
查看>>
Linux下map hash_map和unordered_map效率比较
查看>>
Python学习笔记(二)网络编程的简单示例
查看>>
RabbitMQ 安装和配置
查看>>
Java8新特性之:Optional
查看>>
Redis简单介绍之(安装篇)
查看>>
网络协议控件,SSH 安全组件/n software Red Carpet Subscription
查看>>
用户画像从入门到挖坑
查看>>
Flask 上下文(Context)原理解析
查看>>
Oracle EBS R12.1安装步骤
查看>>
oracle db_nk_cache_size
查看>>
MSSQLServer将远端数据库保存到本地
查看>>
mysql行转列
查看>>
使用 firefox 的开发者工具与 DIG 命令行工具,来分析访问站点时的网络连接与 HTTP 请求和响应...
查看>>
jetspeed教程翻译——jetexpress项目门户的自定义
查看>>
华为usg6380 ssh 配置方法
查看>>
抽象工厂模式(Abstract Factory)
查看>>
zval_dtor与zval_ptr_dtor的区别
查看>>