[关闭]
@XQF 2018-03-07T22:56:12.000000Z 字数 1845 阅读 1150

如何求数组两两相加等于20的组合种数?

数据结构与算法


此类问题是XXX几个数相加等于一个定值的问题范本,。,LeetCode上这种问题很多。有些题是说明数组元素可以重复,有些是只能出现一次

1.两两相加为20

先把数组排序,然后分别从前往后和从后往前两个指针遍历。

  1. public class Test {
  2. public List<List<Integer>> findSum(int[] nums, int k) {
  3. if (nums.length == 0 || nums == null) {
  4. return null;
  5. }
  6. Arrays.sort(nums);
  7. System.out.println(Arrays.toString(nums));
  8. int left = 0;
  9. int right = nums.length - 1;
  10. List<List<Integer>> result = new ArrayList<>();
  11. while (left < right) {
  12. int temp = nums[left] + nums[right];
  13. if (temp == k) {
  14. List<Integer> item = new ArrayList<>();
  15. item.add(nums[left]);
  16. item.add(nums[right]);
  17. System.out.println("item: " + item);
  18. result.add(item);
  19. left++;
  20. } else if (temp > k) {
  21. right--;
  22. } else {
  23. left++;
  24. }
  25. }
  26. return result;
  27. }
  28. public static void main(String[] args) {
  29. int[] nums = {1, 7, 17, 2, 6, 3, 14};
  30. Test t = new Test();
  31. List<List<Integer>> result = t.findSum(nums, 20);
  32. System.out.println(result);
  33. }
  34. }

思路很清晰,。,。夹逼,。,可是这是指定两个元素,要是没有指定元素尼,。,。,没有办法夹逼了

2.dfs深度优先遍历(不指定元素个数版)

还有点小问题,。,为什么最后结果不对为空。其他扩展版比如元素可重复,指定个数,。指定个数在计算的时候加一个conunter就是了

  1. public class Test {
  2. public List<List<Integer>> findSum(int[] nums, int target) {
  3. if (nums.length == 0 || nums == null) {
  4. return null;
  5. }
  6. List<List<Integer>> result = new ArrayList<>();
  7. List<Integer> item = new ArrayList<>();
  8. Arrays.sort(nums);
  9. System.out.println(Arrays.toString(nums));
  10. dfs(0, nums, target, item, result);
  11. return result;
  12. }
  13. public void dfs(int left, int[] nums, int target, List<Integer> item, List<List<Integer>> result) {
  14. if (target < 0) {
  15. return;
  16. }
  17. if (target == 0) {
  18. System.out.println("item:" + item);
  19. result.add(item);
  20. System.out.println("result" + result);
  21. return;
  22. }
  23. for (int i = left; i < nums.length; i++) {
  24. int newTarget = target - nums[i];
  25. item.add(nums[i]);
  26. dfs(i + 1, nums, newTarget, item, result);
  27. item.remove(item.size() - 1);
  28. }
  29. }
  30. public static void main(String[] args) {
  31. int[] nums = {1, 7};
  32. Test t = new Test();
  33. List<List<Integer>> result = t.findSum(nums, 8);
  34. System.out.println(result);
  35. }
  36. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注