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

使用DFS,与Combination Sum类似的思路,只是判断size即可。

public List> combine(int n, int k) { ArrayList> at=new ArrayList>(); if(n<=0||n lt=new ArrayList(); dfs(n,k,1,lt,at); return at; } private void dfs(int n,int k,int start,List lt,ArrayList> at){ if(lt.size()==k){ at.add(new ArrayList(lt)); return; } for(int i=start; i<=n; i++){ lt.add(i); dfs(n,k,i+1,lt,at); lt.remove(lt.size()-1); } }



【java|Combinations】

    推荐阅读