77. Combinations

来源:互联网 发布:知敬畏,守底线,强党性 编辑:程序博客网 时间:2024/06/10 02:47

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],]
传统递归方法求解。因为不考虑排列问题,所以这里设置start。代码如下:

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

0 0
原创粉丝点击