LeetCode:39. Combination Sum(Medium)
2024-09-30 09:43:39
1. 原题链接
https://leetcode.com/problems/combination-sum/description/
2. 题目要求
给定一个整型数组candidates[ ]和目标值target,找出数组中累加之后等于target的所有元素组合
注意:(1)数组中的每一个元素可以重复用;(2)数组中不存在重复元素;(3)数组中都是正整数
3. 解题思路
采用迭代的方法检验所有元素组合
4. 代码实现
import java.util.ArrayList;
import java.util.List; public class CombinationSum39 {
public static void main(String[] args) {
CombinationSum39 cs = new CombinationSum39();
int[] candidates = {,,,};
for (List l1:cs.combinationSum(candidates,)){
System.out.println(l1.toString());
System.out.println();
} }
public List<List<Integer>> combinationSum(int[] candidates, int target) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
combinationSum(result,new ArrayList<Integer>(),candidates,target,);
return result;
}
public void combinationSum(List<List<Integer>> result, List<Integer> cur, int[] candidates, int target,int start) {
if (target > ) {
for (int i = start;i < candidates.length;i++) {
cur.add(candidates[i]);
combinationSum(result, cur, candidates, target-candidates[i],i);
cur.remove(cur.size() - );
}
}
if (target == )
result.add(new ArrayList<Integer>(cur));
}
}
最新文章
- idea打包java可执行jar包
- Win7快速启动栏
- Android入门(三)Activity-生命周期与启动模式
- [问题2014A03] 复旦高等代数 I(14级)每周一题(第五教学周)
- php模式设计之 观察者模式
- [转] - 使用Qt作窗口截屏(含源码)
- 使用记事本+CSC编译程序
- POJ 3436 ACM Computer Factory
- Centos启动默认打开网络
- 关于div包裹img,底下多出3px间隙的问题
- 【协议】3、HTTP 协议入门
- 几种常见数据库的driverClassName和url
- phalcon断点调试(phpStorm+xdebug)
- 在windows10上创建ASP.NET mvc5+Memcached服务
- .Net下SQLite的DBHelp
- No Spring WebApplicationInitializer types detected on classpath异常的解决
- 使用webgl(three.js)搭建一个3D智慧园区、3D建筑,3D消防模拟,web版3D,bim管理系统——第四课
- php ul li 分类
- Developer Express控件gridcontrol中gridView的某一个单元格是否可以自由输入
- 创建view,保存GROUP_CONCAT数据