给定数组A和目标值x,求出A中的所有组合使其和为目标值,A中的数值可重复使用。
例如:A = [2, 3, 6, 7] , x = 7
结果: [[2, 2, 3], [7]]
我目前写出的程序如下,主要用到递归和回溯,希望有大佬能帮忙指点,能不能给出更好的方案。
public class Test {
public static void main(String[] args) {
Solution means = new Solution();
int[] A = new int[]{2,3,6,7};
int x = 7;
means.toSum(A, x);
for (int i = 0; i < means.res.size() - 1; ++ i) {
if (means.isSame(means.res.get(i), means.res.get(i + 1))) {
means.res.remove(i + 1);
i--;
}
}
System.out.println(means.res);
}
}
class Solution {
List<List<Integer>> res = new ArrayList<>();
public void toSum(int[] A, int x) {
List<Integer> arr = new ArrayList<>();
asist(A,x,arr);
}
public void asist(int[] A, int x, List<Integer> arr) {
for (int i = 0; i < A.length; ++ i) {
if (A[i] > x) continue;
else if (A[i] < x) {
arr.add(A[i]);
asist(A, x - A[i], arr);
arr.remove(arr.size() - 1);
}
else if (A[i] == x) {
arr.add(A[i]);
res.add(new ArrayList<>(arr));
arr.remove(arr.size() - 1);
}
}
}
public boolean isSame(List<Integer> list1, List<Integer> list2) {
if (list1.size() != list2.size()) return false;
HashMap<Integer, Integer> map = new HashMap<>();
for (int i = 0; i < list1.size(); ++ i) {
if (map.get(list1.get(i)) != null) map.put(list1.get(i), map.get(list1.get(i)) + 1);
else map.put(list1.get(i), 1);
}
for (int i = 0; i < list1.size(); ++ i) {
if (map.get(list2.get(i)) == null) return false;
map.put(list2.get(i), map.get(list2.get(i)) - 1);
}
for (int i = 0; i < list1.size(); ++ i) {
if (map.get(list2.get(i)) != 0) return false;
}
return true;
}
}