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.
- 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] ]
题目:给定一个数组和一个目标值target,寻找数组中相加结果等于target的组合,可以重复。这道题目昨天下班前就看了,可是下班了就着急去打球,一点都静不下来思考。思路就是用回溯法,但当时静不下来,思考了半天也没个结果。今天把这道题目补上。
思路:回溯法就是要寻找一个解空间,按照题目的意思,2*n+3*m + 6*x+7*z=7即可,寻找n,m,x,y的组合就行了。
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>> combinationSum(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++) {
for(int j = 0; j < n[i];j++) {
l.add(can[i]);
sum = sum + can[i];
}
}
if(sum == target) {
list.add(l);
}
} else {
for(int i = 0; i <= target/can[t];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++) {
for(int j = 0; j < n[i];j++) {
sum = sum + can[i];
}
}
if(sum > target) {
return false;
}
return true;
}
}
提交之后看了下时间,相当后面,改进几个for循环,从81ms提高到47ms。百度了一位网友的做法,提交直接12ms,现在贴上他的解法,比我的简洁的多,效率也更高。
public class Solution {
List<List<Integer>> ans = new ArrayList<List<Integer>>();
int[] cans = {};
public List<List<Integer>> combinationSum(int[] candidates, int target) {
this.cans = candidates;
Arrays.sort(cans);
backTracking(new ArrayList(), 0, target);
return ans;
}
public void backTracking(List<Integer> cur, int from, int target) {
if (target == 0) {
List<Integer> list = new ArrayList<Integer>(cur);
ans.add(list);
} else {
for (int i = from; i < cans.length && cans[i] <= target; i++) {
cur.add(cans[i]);
backTracking(cur, i, target - cans[i]);
cur.remove(new Integer(cans[i]));
}
}
}
}