组合

组合给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。

题目:

示例:

输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]

解题思路:典型的回溯算法问题

class Solution {
    
    private List<List<Integer>> ans = new ArrayList();
    
    public List<List<Integer>> combine(int n, int k) {
        combine(n, k, new ArrayList(), 1);
        return ans;
    }
    
    private void combine(int n, int k, List<Integer> list, int cur) {
        if(list.size() == k) {
            ans.add(new ArrayList(list));
            return ;
        }
        
        for(int i = cur; i <= n; i++) {
            list.add(i);
            combine(n, k, list, i + 1);
            list.remove((Integer) i);
        }
    }
}
原文地址:https://www.cnblogs.com/katoMegumi/p/13924586.html