[leetcode-77]Combinations(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> res,List 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> combine(int n, int k) {
        List> res = new LinkedList<>();
        List tmpList = new LinkedList<>();
        solve(res,tmpList,n,k,1);
        return res;
    }
}

你可能感兴趣的:(leetcode)