首页 > 代码库 > Leetcode-Combinations
Leetcode-Combinations
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],]
Have you met this question in a real interview?
Analysis:
We need consider the boundary and the return condition very carefully!
Solution:
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 }
Leetcode-Combinations
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。