标签:style blog io color ar os sp for div
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], ]
1 public class Solution { 2 public List<List<Integer>> combine(int n, int k) { 3 List<List<Integer>> resSet = new ArrayList<List<Integer>>(); 4 if (n==0 || k==0) return resSet; 5 List<Integer> curList = new ArrayList<Integer>(); 6 combineRecur(resSet,curList,1,k,n,k); 7 return resSet; 8 } 9 10 public void combineRecur(List<List<Integer>> resSet, List<Integer> curList, int curIndex, int numLeft, int n, int k){ 11 if (numLeft==1){ 12 for (int i=curIndex;i<=n;i++){ 13 curList.add(i); 14 List<Integer> temp = new ArrayList<Integer>(); 15 temp.addAll(curList); 16 resSet.add(temp); 17 curList.remove(curList.size()-1); 18 } 19 return; 20 } 21 22 23 for (int i=curIndex;i<=n-numLeft+1;i++){ 24 curList.add(i); 25 combineRecur(resSet,curList,i+1,numLeft-1,n,k); 26 curList.remove(curList.size()-1); 27 } 28 } 29 30 }
标签:style blog io color ar os sp for div
原文地址:http://www.cnblogs.com/lishiblog/p/4101019.html