import java.util.*; public class Solution { private List<List<Integer>> res = new ArrayList<>(); /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param k int整型 * @param n int整型 * @return int整型二维数组 */ public int[][] combination (int k, int n) { // write code here if (n < 1 || k < 1) { return new int[0][0]; } backtrack(k, 1, n, new ArrayList<>()); int[][] matrix = new int[res.size()][k]; for (int i = 0; i < matrix.length; i++) { List<Integer> list = res.get(i); for (int j = 0; j < list.size(); j++) { matrix[i][j] = list.get(j); } } return matrix; } private void backtrack(int k, int start, int target, List<Integer> list) { if (list.size() == k && target == 0) { res.add(new ArrayList<>(list)); return; } for (int i = start; i <= 9; i++) { if (target - i < 0) { break; } target -= i; list.add(i); backtrack(k, i + 1, target, list); target += i; list.remove(list.size() - 1); } } }