77. 组合

给定两个整数 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值