思路是 就像人脑枚举这些组合每次加一个递增的数字 eg 1234 3个数字combine
1
12
123 add
13
134 add
2
23
234 add
注意java的pass by reference。 res.add( list )的话 之后再改变list res里面的list也会变 所以要new 一个list
public class Solution { public List<List<Integer>> combine(int n, int k) { List<List<Integer>> res = new ArrayList<List<Integer>>(); List<Integer> list = new ArrayList<Integer>(); helper ( res, list, 1, n, k); return res; } public void helper ( List<List<Integer>> res, List<Integer> list, int next, int n, int k ){ if ( list.size() == k ){ res.add(new ArrayList(list)); return; } while ( next <= n ){ list.add( next ); helper ( res, list, next + 1, n, k ); list.remove( list.size() - 1); next ++; } return; } }