1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| public class SumLeetcode15 {
static List<List<Integer>> threeSum(int[] nums) { Arrays.sort(nums); List<List<Integer>> result = new LinkedList<>(); dfs(3, 0, nums.length - 1, 0, nums, new LinkedList<>(), result); return result; }
static void dfs(int n, int i, int j, int target, int[] nums, LinkedList<Integer> stack, List<List<Integer>> result) { if (n == 2) { twoSum(i, j, nums, target, stack, result); return; } for (int k = i; k < j - (n - 2); k++) { if (k > i && nums[k] == nums[k - 1]) { continue; } stack.push(nums[k]); dfs(n - 1, k + 1, j, target - nums[k], nums, stack, result); stack.pop(); } }
static int count;
static public void twoSum(int i, int j, int[] numbers, int target, LinkedList<Integer> stack, List<List<Integer>> result) { count++; while (i < j) { int sum = numbers[i] + numbers[j]; if (sum < target) { i++; } else if (sum > target) { j--; } else { ArrayList<Integer> list = new ArrayList<>(stack); list.add(numbers[i]); list.add(numbers[j]); result.add(list); i++; j--; while (i < j && numbers[i] == numbers[i - 1]) { i++; } while (i < j && numbers[j] == numbers[j + 1]) { j--; } } } }
public static void main(String[] args) { long start = System.currentTimeMillis(); int[] candidates = {-4, -1, -1, 0, 0, 1, 1, 2}; System.out.println("数据量:" + candidates.length); System.out.println(threeSum(candidates)); System.out.println("耗费时间:" + (System.currentTimeMillis() - start)); System.out.println("递归次数:" + count); } }
|