77. Combinations
阿新 • • 發佈:2017-05-30
topic pre btn ted oss ret pytho mat lin
題目:
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], ]
Hide Tags Backtracking
鏈接: http://leetcode.com/problems/combinations/
5/29/2017
25ms, 75%
1 publicclass Solution { 2 public List<List<Integer>> combine(int n, int k) { 3 List<List<Integer>> ret = new ArrayList<>(); 4 if (n < k) return ret; 5 6 ArrayList<Integer> list = new ArrayList<Integer>(); 7 combination(n, k, ret, list, 1);8 return ret; 9 } 10 11 private void combination(int n, int k, List<List<Integer>> ret, ArrayList<Integer> list, int pos) { 12 if (list.size() == k) { 13 ret.add(new ArrayList<Integer>(list)); 14 return; 15 } 16 for(int i = pos; i <= n; i++) { 17 list.add(i); 18 combination(n, k, ret, list, i + 1); 19 list.remove(list.size() - 1); 20 } 21 } 22 }
別人的答案
這個不理解
https://discuss.leetcode.com/topic/12537/a-short-recursive-java-solution-based-on-c-n-k-c-n-1-k-1-c-n-1-k
iterative方法,還沒有理解
https://discuss.leetcode.com/topic/8543/iterative-java-solution
Python神人
https://discuss.leetcode.com/topic/14626/1-liner-3-liner-4-liner
更多討論
https://discuss.leetcode.com/category/85/combinations
77. Combinations