77. 组合

怼烎@ 2023-10-04 08:31 28阅读 0赞

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

示例:

  1. 输入: n = 4, k = 2
  2. 输出:
  3. [
  4. [2,4],
  5. [3,4],
  6. [2,3],
  7. [1,2],
  8. [1,3],
  9. [1,4],
  10. ]
  11. package Solution77;
  12. import java.util.ArrayList;
  13. import java.util.List;
  14. class Solution5 {
  15. public List<List<Integer>> combine(int n, int k) {
  16. List<List<Integer>> result = new ArrayList<List<Integer>>();
  17. int elements[] = new int[n];
  18. for (int i = 0; i < n; i++) {
  19. elements[i] = i + 1;
  20. }
  21. for (int i = 0; i < (1 << n); i++) {
  22. if (Integer.bitCount(i) == k) {
  23. ArrayList<Integer> temp = new ArrayList<Integer>();
  24. for (int j = 0; j < n; j++) {
  25. if ((i & (1 << j)) > 0) {
  26. temp.add(elements[j]);
  27. }
  28. }
  29. result.add(temp);
  30. }
  31. }
  32. return result;
  33. }
  34. public static void main(String[] args) {
  35. Solution5 sol = new Solution5();
  36. int n = 4;
  37. int k = 2;
  38. System.out.println(sol.combine(n, k));
  39. }
  40. }

watermark_type_ZmFuZ3poZW5naGVpdGk_shadow_10_text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2FsbHdheTI_size_16_color_FFFFFF_t_70

继续优化

  1. package Solution77;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. class Solution8 {
  5. public List<List<Integer>> combine(int n, int k) {
  6. List<List<Integer>> result = new ArrayList<List<Integer>>();
  7. for (int i = 0; i < (1 << n); i++) {
  8. if (Integer.bitCount(i) == k) {
  9. ArrayList<Integer> temp = new ArrayList<Integer>();
  10. for (int j = 0; j < n; j++) {
  11. if ((i & (1 << j)) > 0) {
  12. temp.add(j + 1);
  13. }
  14. }
  15. result.add(temp);
  16. }
  17. }
  18. return result;
  19. }
  20. public static void main(String[] args) {
  21. Solution8 sol = new Solution8();
  22. int n = 4;
  23. int k = 2;
  24. System.out.println(sol.combine(n, k));
  25. }
  26. }

发表评论

表情:
评论列表 (有 0 条评论,28人围观)

还没有评论,来说两句吧...

相关阅读

    相关 77. 组合

    > 保持忙碌。——《人性的优点》 77. 组合 给定两个整数 n 和 k,返回范围 \[1, n\] 中所有可能的 k 个数的组合。 你可以按 任何顺序 返回答案。

    相关 77.组合

    第77题. 组合 题干描述 解题思路 回溯法三部曲 1. 递归函数的返回值以及参数 2. 回溯函数终止条件 3.

    相关 77.组合

    下面我通过讲解一道回溯、递归类型的题目帮助大家快速的理解递归的用法 题目描述: > 给定两个整数 n 和 k,返回范围 \[1, n\] 中所有可能的 k 个数的组合。你

    相关 77. 组合

    给定两个整数 n 和 k,返回 1 ... n 中所有可能的 k 个数的组合。 示例: 输入: n = 4, k = 2 输出: [ [