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.
- 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] ]
题目:和上一题类似,只不过这次数组存在重复,且相加时不能多个。
思路:直接用上一题的代码,修改了限制条件,虽然提交成功,但是耗时244ms,应该是勉强通过。
public class Solution {
List<List<Integer>> list = new ArrayList<List<Integer>>();
static int len;
static int target;
static int[] n;
static int[] can;
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
this.len = candidates.length;
this.n = new int[len];
this.can = candidates;
this.target = target;
Arrays.sort(can);
helper(0);
return list;
}
public void helper(int t) {
if(t >= len) {
int sum = 0;
List<Integer> l = new ArrayList<Integer>();
for(int i = 0; i < len;i++) {
if(n[i] !=0) {
l.add(can[i]);
sum = sum + can[i];
}
if(sum > target) {
break;
}
}
if(sum == target) {
if(!list.contains(l))
list.add(l);
}
} else {
for(int i = 0; i <= 1;i++) {
n[t] = i;
if(isValid(t)) {
helper(t+1);
}
}
}
}
public boolean isValid(int t) {
int sum = 0;
for(int i = 0; i <= t;i++) {
if(n[i] !=0) {
sum = sum + can[i];
}
}
if(sum > target) {
return false;
}
return true;
}
}下面是另外一种做法,也是在上一题的基础上修改限制条件,简洁高效,请参考这种做法。
public class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
int[] num = {};
public List<List<Integer>> combinationSum2(int[] num, int target) {
this.num = num;
Arrays.sort(num);
backTracking(new ArrayList<Integer>(), 0, target);
return ans;
}
public void backTracking(List<Integer> cur, int from, int tar) {
if (tar == 0) {
//如果当前解不在结果集中,把其加入到结果集中
List<Integer> list = new ArrayList<Integer>(cur);
if(!ans.contains(list))
ans.add(list);
}
for (int i = from; i < num.length && num[i] <= tar; i++) {
cur.add(num[i]);
backTracking(cur, i + 1, tar - num[i]);
cur.remove(new Integer(num[i]));
}
}
}今天聊点废话,这两天特性提交验收,测试是一个新来的妹子,啥都不会,但是会发现问题,测的很仔细,还发现的了以严重的问题。特性中使用echarts实时更新数据,但是页面长时间停留会发生崩溃的情况,妹子是放了一晚上第二天来都崩溃了,猜测是内存泄漏了,早上我在自己的环境上复现了一把,把监控时间间隔缩短成1秒,大概过了3个小时,页面崩溃了,因为时间太长,中间无法一直关注内存的变化,只发现内存使用率会上升到78百m,然后有慢慢降下来。下午把监控时间间隔改成10ms,通过查看chrome devToos查看,发现array的内存占用率会上升的很快,一直到1g,子啊深入的了解,发现是创建了很多一样的array对象,导致内存使用率直线上升,因为更新数据的时候只涉及到一个定时器中的addData()方法。所以就怀疑是这个方法导致的,addData是echarts提供的更新数据的一个方法,当时就改成了setOption()方法,同样是10ms的刷新频率,内存使用率没有显著的提高,恢复到正常的监控时间间隔,一晚上页面也没崩溃。现在还没仔细看过addData的代码,下周有空找找原因。今天这个问题暂时是解决了,通过这件事,也得到一些经验,遇见这种完全不熟悉的问题,别慌,先根据最初的猜测去复现问题,确定问题的原因。

本文探讨了给定一组候选数和目标数时如何找出所有可能的组合,使得这些候选数之和等于目标数。提供了两种解决方案,一种是通过递归实现,另一种则是采用回溯法。同时分享了一个关于内存泄漏的实际案例。
341

被折叠的 条评论
为什么被折叠?



