1. 程式人生 > >LeetCode 77. 組合 Combinations

LeetCode 77. 組合 Combinations

8-4 組合問題 Combinations

題目: LeetCode 77. 組合

給定兩個整數 n 和 k,返回 1 … n 中所有可能的 k 個數的組合。

示例:

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

import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;

/// 77. Combinations
/// https://leetcode.com/problems/combinations/description/
/// 時間複雜度: O(n^k) /// 空間複雜度: O(k) public class Solution { private ArrayList<List<Integer>> res; public List<List<Integer>> combine(int n, int k) { res = new ArrayList<List<Integer>>(); if(n <= 0 || k <= 0 || k > n) return res;
LinkedList<Integer> c = new LinkedList<Integer>(); generateCombinations(n, k, 1, c); return res; } // 求解C(n,k), 當前已經找到的組合儲存在c中, 需要從start開始搜尋新的元素 private void generateCombinations(int n, int k, int start, LinkedList<Integer> c){ if(c.size
() == k){ res.add((List<Integer>)c.clone()); return; } for(int i = start ; i <= n ; i ++){ c.addLast(i); generateCombinations(n, k, i + 1, c); c.removeLast(); } return; } private static void printList(List<Integer> list){ for(Integer e: list) System.out.print(e + " "); System.out.println(); } public static void main(String[] args) { List<List<Integer>> res = (new Solution()).combine(4, 2); for(List<Integer> list: res) printList(list); } }
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;

/// 77. Combinations
/// https://leetcode.com/problems/combinations/description/
/// 時間複雜度: O(n^k)
/// 空間複雜度: O(k)
public class Solution {

    private ArrayList<List<Integer>> res;

    public List<List<Integer>> combine(int n, int k) {

        res = new ArrayList<List<Integer>>();
        if(n <= 0 || k <= 0 || k > n)
            return res;

        LinkedList<Integer> c = new LinkedList<Integer>();
        generateCombinations(n, k, 1, c);

        return res;
    }

    // 求解C(n,k), 當前已經找到的組合儲存在c中, 需要從start開始搜尋新的元素
    private void generateCombinations(int n, int k, int start, LinkedList<Integer> c){

        if(c.size() == k){
            res.add((List<Integer>)c.clone());
            return;
        }

        // 還有k - c.size()個空位, 所以, [i...n] 中至少要有 k - c.size() 個元素
        // i最多為 n - (k - c.size()) + 1
        for(int i = start ; i <= n - (k - c.size()) + 1 ; i ++){
            c.addLast(i);
            generateCombinations(n, k, i + 1, c);
            c.removeLast();
        }

        return;
    }

    private static void printList(List<Integer> list){
        for(Integer e: list)
            System.out.print(e + " ");
        System.out.println();
    }

    public static void main(String[] args) {

        List<List<Integer>> res = (new Solution()).combine(4, 2);
        for(List<Integer> list: res)
            printList(list);
    }
}