问个递归的问题# JobHunting - 待字闺中
m*1
1 楼
不好意思,我基础太差了,在leetcode上遇到好几道类似的题目,每次在同一个地方总
是弄不明白,希望同学们能帮我讲解下,帮助和我一样有困惑的人,先谢谢大家啦!
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],
]
//solution
public ArrayList> combine(int n, int k)
{
ArrayList> res= new ArrayList
>();
ArrayList temp= new ArrayList ();
dfs(res,temp,n,k,1);
return res;
}
void dfs(ArrayList> res,ArrayList temp, int
n, int k, int level)
{
if(temp.size==k)
{
res.add(new ArrayList(temp));
return;
}
for(int i=level;i<=n;i++)
{
temp.add(i);
dfs(res,temp,n,k,i+1);
temp.remove(temp.size()-1); //这个地方为什么要这样处理呢,
remove的不是i本身(上面刚添加的元素),而是remove temp.size()-1
}
}
是弄不明白,希望同学们能帮我讲解下,帮助和我一样有困惑的人,先谢谢大家啦!
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],
]
//solution
public ArrayList
{
ArrayList
>();
ArrayList
dfs(res,temp,n,k,1);
return res;
}
void dfs(ArrayList
n, int k, int level)
{
if(temp.size==k)
{
res.add(new ArrayList
return;
}
for(int i=level;i<=n;i++)
{
temp.add(i);
dfs(res,temp,n,k,i+1);
temp.remove(temp.size()-1); //这个地方为什么要这样处理呢,
remove的不是i本身(上面刚添加的元素),而是remove temp.size()-1
}
}