`

Combinations

阅读更多
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],
]

有关组合的问题,给定了一个限定条件,长度为k的组合。同样用回溯法,回溯的条件就是每个结果的长度为k。往前搜索的时候,每次都加1,知道遍历完所有的可能。代码如下:
public class Solution {
    public List<List<Integer>> combine(int n, int k) {
        LinkedList<Integer> list = new LinkedList<Integer>();
        List<List<Integer>> llist = new LinkedList<List<Integer>>();
        if(n < 1) return llist;
        getCombine(1, n, k, list, llist);
        return llist;
    }
    public void getCombine(int start, int n, int k, LinkedList<Integer> list, List<List<Integer>> llist) {
        if(list.size() == k) {
            llist.add(new LinkedList<Integer>(list));
            return;
        }
        for(int i = start; i <= n; i++) {
            list.add(i);
            getCombine(i + 1, n, k, list, llist);
            list.removeLast();
        }
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics