[LeetCode]Combinations

来源:互联网 发布:阿里云数据库怎么用 编辑:程序博客网 时间:2024/05/22 02:22

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],]
public class Solution {List<Integer> list = new ArrayList<Integer>();List<List<Integer>> res = new ArrayList<>();public List<List<Integer>> combine(int n, int k) {if (n < k) {return res;}combine(n,k,0,1);return res;}private void combine(int n, int k, int len, int start){    if(len == k){    List<Integer> lin = new ArrayList<>(list);    res.add(lin);    return;    }        for(int i=start;i<=n;i++){    list.add(i);    combine(n,k,len+1,i+1);    list.remove(Integer.valueOf(i));    }    }}





0 0
原创粉丝点击