leetcode解题方案--039-- CombinationSum
来源:互联网 发布:linux 查看数据包 编辑:程序博客网 时间:2024/05/29 10:44
题目
Given a set of candidate numbers (C) (without duplicates) 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.
The solution set must not contain duplicate combinations.
For example, given candidate set [2, 3, 6, 7] and target 7,
A solution set is:
分析
这道题是求所有和为target的情况。和数独差不多。挨个试。
每当添加一个新值时,如果仍未达到target,则将target-当前和作为下一个target。并创建一个新的分支。如:
刚开始列表只有一个元素
2
2 2
2 3
2 6!
2 7!
第二次
2 2 2
2 2 3*
2 2 6!
2 2 7!
2 3 3!
2 3 6!
2 3 7!
class Solution { public static List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> ret = new LinkedList<>(); // 2 3 6 7 //7;2 2 3 Arrays.sort(candidates); // sort the array recurse(new ArrayList<Integer>(), target, candidates, 0, ret); return ret; } private static void recurse(List<Integer> list, int target, int[] candidates, int index, List<List<Integer>> result) { if (target == 0) { result.add(list); return; } for (int i = index; i<candidates.length; i++) { int newTar = target-candidates[i]; if (newTar>=0) { List<Integer> copy = new ArrayList<>(list); copy.add(candidates[i]); recurse(copy, newTar,candidates, i, result); } else { break; } } }}
阅读全文
0 0
- leetcode解题方案--039-- CombinationSum
- leetcode解题方案--040-- CombinationSum
- LeetCode之求组合数之和CombinationSum
- leetcode解题方案--001--TwoSum
- leetcode解题方案--002--AddTwoNumbers
- leetcode解题方案--003--LongestSubstringWithoutRepeatingCharacters
- leetcode解题方案--004--MedianofTwoSortedArrays
- leetcode解题方案--046--Permutations
- leetcode解题方案--055--jumpGame
- leetcode解题方案--061--RotateList
- [Leetcode] Duplicate Emails 我的解题方案
- leetcode解题方案--005--Longest Palindromic Substring
- leetcode解题方案--012--Integer to Roman
- leetcode解题方案--013--Roman to Integer
- leetcode解题方案--014--Longest Common Prefix
- leetcode解题方案--015--3 sum
- leetcode解题方案--016--3 sum closest
- leetcode解题方案--018--4 sum
- 机器学习 基础
- 将毫秒转换为时间(HH:ss:mm)
- DAY1之Python复习
- 「蓝光」「720/1080p」「HR-HDTV」等视频制式都是什么意思?清晰度对比如何?
- mysql安装卡在Type and NetWorking,无法继续安装。
- leetcode解题方案--039-- CombinationSum
- 双线性插值
- 火狐浏览器所有历史版本下载地址
- 前端修改字体大小,google限制字体最小
- 测试服务器上直接修改properties文件导致OOM的问题
- Hibernate理解2:hibernate的运用理解
- 编写一个JFrame窗口
- 用easyui时遇到一对一 外键关联时 数据绑定
- Intent的详解