/* * 77. Combinations * 2015.12.16 by Mingyang * 这里有个一个start的多的参数以后就可以保证所有序列按顺序输出的,并且不会重复 12-13-14-23-24-34 * 1.长度标准:无 * 2.可选的范围:从start到最后一个 * 3.往前走一步:可以往上下左右四个方向分别加1 * 4.后退一步:mark unvisited * 5.特别的case:出界了,访问过了,或者达标了 * 6.关于重复:无 */ public static List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<List<Integer>>(); if (n <= 0 || n < k) return res; List<Integer> item = new ArrayList<Integer>(); dfs2(n, k, 1, item, res);// because it need to begin from 1-------从1开始的哦 return res; } private static void dfs2(int n, int k, int start, List<Integer> item,List<List<Integer>> res) { if (item.size() == k) { res.add(new ArrayList<Integer>(item));// because item is ArrayList<T> so it will not disappear from stack to stack return; } for (int i = start; i <= n; i++) { // 这里多加了一个start,这样就不用再判断重复了 item.add(i); dfs2(n, k, i + 1, item, res); item.remove(item.size() - 1); } }