【Leetcode】77. Combinations

来源:互联网 发布:77pepecom现在域名 编辑:程序博客网 时间:2024/06/08 21:08

先贴代码:

转载自:http://blog.csdn.net/happyaaaaaaaaaaa/article/details/51564160

public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> resList = new ArrayList<List<Integer>>();
        List<Integer> temp = new ArrayList<Integer>();
        dfs(resList,temp,n,k,1);
        return resList;
    }
    private void dfs(List<List<Integer>> res,List<Integer> temp,int n,int k,int m){
        if(k == 0){
            res.add(new ArrayList<Integer>(temp));
        }
        for(int i=m;i<=n;i++){
            temp.add(i);
            dfs(res,temp,n,k-1,i+1);
            temp.remove(temp.size()-1);//吐出当前这个
        }
    }
}

该解法只用了一个额外的空间,通过不断的递归来解决这个问题。

每次如果选中一个节点,进入递归,当元素选满的时候退出。

每次递归结束的时候弹出最后一个节点,随后进入下次递归,从而遍历了所有的可能结果。


贴上运行结果:(还行)



PS:对于深度优先和广度优先树的题目总感觉无从下手~~~留坑,等我找到提升速度的方式

0 0