题解 | #牛牛的三元组问题#
牛牛的三元组问题
https://www.nowcoder.com/practice/72c6d735fb1144a2ba162976a4510839
import java.util.*; public class Solution { /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param nums int整型一维数组 * @return int整型二维数组 */ public int[][] findTriplets (int[] candidates) { int n = candidates.length; List<List<Integer>> ans = new ArrayList<>(); Arrays.sort(candidates); dfs(candidates, n, 0, 0, new ArrayList<>(), ans); int[][] anss = new int[ans.size()][3]; for (int i = 0; i < ans.size(); i++) { List<Integer> integers = ans.get(i); anss[i][0] = integers.get(0); anss[i][1] = integers.get(1); anss[i][2] = integers.get(2); } return anss; } public void dfs(int[] candidate, int n, int idx, int target, List<Integer> list, List<List<Integer>> ans) { if (target == 0&&list.size()==3) { ans.add(new ArrayList<>(list)); return ; } if (list.size()>3) return; for (int i = idx; i < n; i++) { if (i > idx && candidate[i] == candidate[i - 1]) { // 剪枝、避免重复 // 因为前面那个同样的数已经经历过dfs,再拿同样的数dfs就会得到重复的答案 continue; } list.add(candidate[i]); dfs(candidate, n, i + 1, target - candidate[i], list, ans); list.remove(list.size() - 1); } } }