leetcode------Combinations
标题: |
Combinations |
通过率: | 30.5% |
难度: | 中等 |
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], ]
到了递归。。我发现我的弱点就是递归。
本题相当于遍历二叉树。应为是正序,不重复,则能做开头的元素就是n-k+1,所以从1开始然后进入迭代,放够k个元素后进行add
具体看代码:
1 public class Solution { 2 private ArrayList<ArrayList<Integer>> arrays = new ArrayList<ArrayList<Integer>>(); 3 public ArrayList<ArrayList<Integer>> combine(int n, int k) { 4 for (int i=1; i<=n-k+1; ++i){ 5 ArrayList<Integer> list = new ArrayList<Integer>(); 6 list.add(i); 7 cal(list, i+1, n, k-1); 8 } 9 return arrays; 10 } 11 public void cal(ArrayList<Integer> list, int start, int end, int k){ 12 if (k == 0){ 13 ArrayList<Integer> result = new ArrayList<Integer>(list); 14 arrays.add(result); 15 } 16 for (int i=start; i<=end; ++i){ 17 list.add(i); 18 cal(list, i+1, end, k-1); 19 list.remove(list.size()-1); 20 } 21 } 22 }