[leetcode-77]Combinations(java)

  • Post author:
  • Post category:java


问题描述:

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],

]

分析:这个很明显的使用递归,结果我还犹豫了一下,猜想会不会TLE,结果还不错。

代码如下:288ms

public class Solution {
     private void solve(List<List<Integer>> res,List<Integer> tmpList,int n,int k,int index){
        if(tmpList.size()==k){
            res.add(new LinkedList<>(tmpList));
            return;
        }
        int size = tmpList.size();
        for(int i = index;i<=n-k+size+1;i++){
            tmpList.add(i);
            solve(res,tmpList,n,k,i+1);
            tmpList.remove(size);
        }
    }
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> res = new LinkedList<>();
        List<Integer> tmpList = new LinkedList<>();
        solve(res,tmpList,n,k,1);
        return res;
    }
}



版权声明:本文为zdavb原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。