求取一个数组中所有的数字组合(和为目标数字)
1.对于一个数组类似:[1,2,3,4,7],寻找可以重复使用每一个数字,组成的集合为目标数7的组合集合。如:
[
[1,1,1,1,1,1,1],
[2,2,2,1],
[3,4],
[3,3,1],
…]
]
使用回溯进行解决,需要注意,原数组数字不可重复。
class Solution{
private List<List<Integer>> ans = new ArrayList<>();
private List<Integer> combaine = new ArrayList<>();
public List<List<Integer>> re(int[] candaines, int target){
}
private void dfs(int[] candaines, int target, int idx){
//到达数组边界返回
if(idx == candaines.length){
return;
}
//满足条件返回
if(target == 0){
ans.add(new ArrayList<Integer>(combaine));
return;
}
dfs(candaines, target, idx+1);
if(target - candaines[idx] >=0){
combaine.add(candaines[idx]);
//由于一个数可以重复取,这里idx不加一
dfs(candaines, target - candaines[idx], idx);
combaine.remove(combaine.size() - 1);
}
}
}
2.同样对于一个数组[1,1,3,2,4],存在重复的数字,每个数字只能用一次。不妨考虑首先对这个数组进行处理,让它不存在重复的数字。可以先进行排序,后将一个重复的数记下它的出现次数。
class Solution {
List<int[]> freq = new ArrayList<int[]>();
List<List<Integer>> ans = new ArrayList<List<Integer>>();
List<Integer> sequence = new ArrayList<Integer>();
public List<List<Integer>> combinationSum2(int[] candidates, int target) {
//排序
Arrays.sort(candidates);
//处理数组
for (int num : candidates) {
int size = freq.size();
if (freq.isEmpty() || num != freq.get(size - 1)[0]) {
freq.add(new int[]{num, 1});
} else {
++freq.get(size - 1)[1];
}
}
dfs(0, target);
return ans;
}
public void dfs(int pos, int rest) {
//符合条件返回
if (rest == 0) {
ans.add(new ArrayList<Integer>(sequence));
return;
}
//越界返回
if (pos == freq.size() || rest < freq.get(pos)[0]) {
return;
}
dfs(pos + 1, rest);
//这是target可以容纳的当前数的个数
//如果这个数不重复,那么most挺好的2233
int most = Math.min(rest / freq.get(pos)[0], freq.get(pos)[1]); //根据次数加和减
for (int i = 1; i <= most; ++i) {
sequence.add(freq.get(pos)[0]);
dfs(pos + 1, rest - i * freq.get(pos)[0]);
}
for (int i = 1; i <= most; ++i) {
sequence.remove(sequence.size() - 1);
}
}
}