Given two integers n and k, return all possible combinations of k numbers out of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[ [2,4], [3,4], [2,3], [1,2], [1,3], [1,4], ]
解题思路:
DFS,JAVA实现如下:
public static void main(String args[]) { List<List<Integer>> list = combine(5, 2); System.out.println(list.size()); for (List<Integer> alist : list) System.out.println(alist + "*"); } static public List<List<Integer>> combine(int n, int k) { List<List<Integer>> list = new ArrayList<List<Integer>>(); if (n <= 0 || k > n) return list; dfs(list, n, k, 0); return list; } static List<Integer> alist = new ArrayList<Integer>(); static void dfs(List<List<Integer>> list, int n, int k, int depth) { if (depth >= k) { list.add(new ArrayList<Integer>(alist)); return; } if (depth == 0) for (int i = 1; i <= n - k + 1; i++) { alist.add(i); dfs(list, n, k, depth + 1); alist.remove(alist.size() - 1); } else for (int i = 1; i <= n - alist.get(alist.size() - 1) + k - depth - 1; i++) { alist.add(alist.get(alist.size() - 1) + i); dfs(list, n, k, depth + 1); alist.remove(alist.size() - 1); } }