【LeetCode】 077. Combinations

来源:互联网 发布:诊疗指南软件下载 编辑:程序博客网 时间:2024/05/24 02:37

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 {    public List<List<Integer>> combine(int n, int k) {        List<List<Integer>> res = new ArrayList<List<Integer>>();        helper(res, new ArrayList<Integer>(), 1, n, k);        return res;    }        private void helper(List<List<Integer>> res, List<Integer> subList, int start, int n, int k) {        if (k == subList.size()) {            res.add(new ArrayList<Integer>(subList));            return;        }        for (int i = start; i <= n; i++) {            subList.add(i);            helper(res, subList, i + 1, n, k);            subList.remove(subList.size() - 1);        }    }}


0 0