77代码随想录--回溯--组合

力扣题目链接(opens new window)

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

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


import java.util.ArrayList;
import java.util.List;

public class Com {

    public static List> combine(int n, int k) {
        List> combinations = new ArrayList<>();
        backtrack(combinations, new ArrayList<>(), 1, n, k);
        return combinations;
    }

    private static void backtrack(List> combinations, List current, int start, int n, int k) {
        if (current.size() == k) {
            combinations.add(new ArrayList<>(current));
            return;
        }

        for (int i = start; i <= n; i++) {
            current.add(i);
            backtrack(combinations, current, i + 1, n, k);
            current.remove(current.size() - 1);
        }
    }

    public static void main(String[] args) {
        List> result = combine(4, 2);
        System.out.println(result);
    }
}

你可能感兴趣的:(代码随想录,hot100,算法,数据结构)