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

本文共 2027 字,大约阅读时间需要 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(); } }}

 

转载于:https://www.cnblogs.com/null00/p/5075503.html

你可能感兴趣的文章
Codeforces 960B(优先队列)
查看>>
语言基础(5):程序内存结构
查看>>
angular filter
查看>>
JLabel作为展现元素时需要注意的事项
查看>>
初次接触git
查看>>
eclipse 导入android工程后找不到R资源
查看>>
室内装修
查看>>
《nginx源代码解析》系列分享专栏
查看>>
2-01 ASCII码与二进制转
查看>>
3-04函数-默认参数
查看>>
vs 编译error1083
查看>>
re 正则模块
查看>>
PHP实用代码片段(二)
查看>>
按时间分区自动建分区表
查看>>
centos7安装golang
查看>>
Go VUE --- vuejs在服务器部署?
查看>>
各种排序算法原理图
查看>>
ASP.NET Core Middleware管道介绍
查看>>
SQL 外键
查看>>
二叉树的三种非递归遍历和层次遍历
查看>>