组合DFS。对其中需要无重复,非降序的要求,只需做个小小的“剪枝”判断就行了。
import java.util.ArrayList; import java.util.Collections; public class Solution { public ArrayList<ArrayList<Integer>> combine(int n, int k) { // Start typing your Java solution below // DO NOT write main() function ArrayList<ArrayList<Integer>> ans = new ArrayList<ArrayList<Integer>>(); int[] combination = new int[k]; dfs(combination, 0, k, n, ans); return ans; } public void dfs(int[] combination, int d, int k, int n, ArrayList<ArrayList<Integer>> arr) { if (d == k) { ArrayList<Integer> a = new ArrayList<Integer>(); for (int i = 0; i < k; i++) { a.add(combination[i]); } Collections.sort(a); arr.add(a); return; } else { for (int i = 0; i < n; i++) { if (d == 0 || i+1 > combination[d-1]) { combination[d] = i+1; dfs(combination, d+1, k, n, arr); } } } } }