offer2-80


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

示例 1:

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

示例 2:

输入: n = 1, k = 1
输出: [[1]]

提示:

  • 1 <= n <= 20
  • 1 <= k <= n

//leetcode submit region begin(Prohibit modification and deletion)
class Solution {
    public List<List<Integer>> combine(int n, int k) {
        List<List<Integer>> result = new ArrayList<>();
        List<Integer> curList = new ArrayList<>();

        combineFunc(result, curList, 1, n, k);
        return result;
    }

    private void combineFunc(List<List<Integer>> result, List<Integer> curList, int i, int n, int k) {
        if (i > n) {
            return;
        }
        curList.add(i);
        if (curList.size() == k) {
            List<Integer> oneRes = new ArrayList<>(curList);
            result.add(oneRes);
        } else {
            combineFunc(result, curList, i + 1, n, k);
        }
        curList.remove(curList.size() - 1);
        combineFunc(result, curList, i + 1, n, k);
    }
}
//leetcode submit region end(Prohibit modification and deletion)

文章作者: 倪春恩
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 倪春恩 !