Given-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], [up], [1,3], [1,4],]
Problem-solving ideas: Dfs,java realized as follows:
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);d FS (list, n, k, depth + 1); Alist.remove (Alist.size () -1);} elsefor (int i = 1; I <= N-alist.get (Alist.size ()-1) + k-depth-1; i++) {Alist.add (Alist.get (Alist.size ()-1) + i);d FS (list, n, k, depth + 1); Alist.remove (Alist.size ()-1);}}
Java for Leetcode 077 combinations