77. Combinations

来源:互联网 发布:js 设置dialog button 编辑:程序博客网 时间:2024/05/21 07:50

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

思路: 回溯法

<span style="font-size:14px;">public class Solution {    public List<List<Integer>> combine(int n, int k) {        List<List<Integer>> res=new ArrayList<List<Integer>>();        combineHelp(1,n,k,new ArrayList<Integer>(),res);        return res;    }        public void combineHelp(int start,int n,int k,List<Integer> list,List<List<Integer>> res){        if(k==0){            res.add(new ArrayList(list));            return;        }        for(;start<=n;start++){            list.add(start);            combineHelp(start+1,n,k-1,list,res);            list.remove(list.size()-1);        }    }}</span>


0 0
原创粉丝点击