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> combine(int n, int k) { LinkedList
list = new LinkedList (); List > llist = new LinkedList
>(); if(n < 1) return llist; getCombine(1, n, k, list, llist); return llist; } public void getCombine(int start, int n, int k, LinkedList
list, List > llist) { if(list.size() == k) { llist.add(new LinkedList
(list)); return; } for(int i = start; i <= n; i++) { list.add(i); getCombine(i + 1, n, k, list, llist); list.removeLast(); } } }