给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。
示例:
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/combinations
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
1 public class Solution { 2 private boolean[] flag = null; 3 private List<List<Integer>> res = null; 4 5 private void helper(int n, int k, int cur,List<Integer> subset){ 6 if (k == 0) { 7 res.add(new ArrayList<>(subset)); 8 return; 9 } 10 for (int i = cur; i <= n; i++) { 11 if (!flag[i]){ 12 if (subset.size() > 0 && subset.get(subset.size()-1) >= i) 13 break; 14 flag[i] = true; 15 subset.add(i); 16 helper(n, k-1, i+1, subset); 17 flag[i] = false; 18 subset.remove(subset.size()-1); 19 } 20 } 21 } 22 23 24 public List<List<Integer>> combine(int n, int k) { 25 flag = new boolean[n+1]; 26 res = new ArrayList<>(); 27 List<Integer> subset = new ArrayList<>(); 28 29 helper(n,k,1,subset); 30 return res; 31 } 32 33 public static void main(String[] args) { 34 List<List<Integer>> combine = new Solution().combine(4, 2); 35 for (List<Integer> e : combine) { 36 System.out.println(e); 37 } 38 } 39 }
原文地址:https://www.cnblogs.com/yfs123456/p/11615464.html
时间: 2024-10-31 08:42:33