LeetCode-39組合總和

給定一個無重複元素的數組 candidates 和一個目標數 target ,找出 candidates 中所有可以使數字和爲 target 的組合。

candidates 中的數字可以無限制重複被選取。

說明:

所有數字(包括 target)都是正整數。
解集不能包含重複的組合。
示例 1:

輸入: candidates = [2,3,6,7], target = 7,
所求解集爲:
[
[7],
[2,2,3]
]
示例 2:

輸入: candidates = [2,3,5], target = 8,
所求解集爲:
[
[2,2,2,2],
[2,3,3],
[3,5]
]

import java.util.Arrays;

public class Combination1 {

    void combinate(int[] in, int target, int[] out, int beginIndex, int outCurIndex) {
        for (int i = beginIndex; i < in.length; i++) {

            out[outCurIndex] = in[i];
            int sum = 0;
            for (int j = 0; j <= outCurIndex; j++) {
                sum += out[j];
            }
            if (sum == target) {
                for (int j = 0; j <= outCurIndex; j++) {
                    System.out.print(String.format("%4d", out[j]));
                }
                System.out.println();
                break;
            }
            if (sum > target) {
                break;
            }

            beginIndex = i;
            combinate(in, target, out, beginIndex, outCurIndex + 1);
        }
    }

    void combinate(int[] in, int target) {
        if (in == null || in.length == 0) return;

        Arrays.sort(in);
        int[] out = new int[target / in[0] + 1];

        combinate(in, target, out, 0, 0);

    }

    public static void main(String[] args) {
        int[] in = new int[] {2, 3, 5};
        Combination1 combination1 = new Combination1();
        combination1.combinate(in, 8);
    }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章