dfs搜索判断。没什么好说的。 第一次做的时候dfs是每一次判断当前数字加不加入list,结果超时。 之后改成了每一次选择一个合理的加入,顺利Ac。 两者比较,前者每次有两个分支,代价是2^n;后者则要远远小于这个量级。
public class Solution {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
public ArrayList<ArrayList<Integer>> combine(int n, int k) {
if( n==0 || k== 0 || k>n )
{
return res;
}
fun( new ArrayList<Integer>(),0,1,n,k );
return res;
}
void fun( ArrayList<Integer> tmp,int count,int st,int n,int k)
{
if( count == k )
{
res.add(tmp);
return;
}
if( n-st+1 <k-count )
{
return;
}
for( int i=st;i<=n;i++ )
{
ArrayList<Integer> temp = new ArrayList<Integer>(tmp);
temp.add(i);
fun(temp,count+1,i+1,n,k);
}
}
}