Combinations

来源:互联网 发布:u盘安装ubuntu系统安装 编辑:程序博客网 时间:2024/05/16 12:28

Given two integers n and k, return all possible combinations ofk 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来求解这个问题

public class Solution {    public List<List<Integer>> combine(int n, int k) {        List<List<Integer>> res = new ArrayList<>();        if(n <= 0 || k > n)            return res;        List<Integer> list = new ArrayList<>();        dfs(n,k,1,list,res);        return res;    }    public void dfs(int n, int k, int start, List<Integer> list, List<List<Integer>> res){        if(list.size() == k) {            res.add(new ArrayList<>(list));            return;        }        for(int i = start; i <= n; i++){            list.add(i);  //添加一个新的元素            dfs(n,k,i+1,list,res);            list.remove(list.size()-1); // 删除刚才添加进去的元素        }    }}


原创粉丝点击