本文主要是介绍leetcode -- 77. Combinations,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目描述
题目难度:Medium
Given two integers n and k, return all possible combinations of k numbers out of 1 … n.
- Example:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
AC代码
class Solution {public List<List<Integer>> combine(int n, int k) {List<List<Integer>> resList = new ArrayList<>();if(n <= 0 || k <= 0 || n < k) return resList;backtracing(n, k, 1, new ArrayList<Integer>(), resList);return resList;}private void backtracing(int n, int k, int start, List<Integer> tmpList, List<List<Integer>> resList){if(k == tmpList.size()) {resList.add(new ArrayList<>(tmpList));return;}for(int i = start;i <= n;i++){tmpList.add(i);backtracing(n, k, i + 1, tmpList, resList);tmpList.remove(tmpList.size() - 1);}}
}
这篇关于leetcode -- 77. Combinations的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!