組合數的和

原題

  Find all possible combinations of k numbers that add up to a number n, given that only numbers from 1 to 9 can be used and each combination should be a unique set of numbers.
Ensure that numbers within the set are sorted in ascending order.
  Example 1:
  Input: k = 3, n = 7
  Output:
  [[1,2,4]]
  Example 2:
  Input: k = 3, n = 9
  Output:
  [[1,2,6], [1,3,5], [2,3,4]]java

題目大意

  尋找全部知足k個數之和等於n的組合,只容許使用數字1-9,而且每一種組合中的數字應該是惟一的。確保組合中的數字以遞增順序排列。算法

解題思路

  回溯法spa

代碼實現

算法實現類.net

import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Solution {

    public List<List<Integer>> combinationSum3(int k, int n) {
        // 用於保存全部結果
        List<List<Integer>> result = new LinkedList<>();
        // 用於保存中間結果
        List<Integer> list = new LinkedList<>();
        // 條件知足就進行解題操做
        if (k > 0 && k <= 9) {
                solve(k, 1, n, 0, list, result);
        }

        // 返回結果
        return result;
    }

    /**
     * 求解方法
     *
     * @param k         每一個解的元素個數
     * @param cur       當前處理第k個元素
     * @param remainder k - cur + 1個元素的和
     * @param prevVal   第cur-1個元素的取值
     * @param list      將解的元素的集合類
     * @param result    保存全部結果的容器
     */
    public void solve(int k, int cur, int remainder, int prevVal, List<Integer> list, List<List<Integer>> result) {
        // 處理最後一個元素
        if (cur == k) {
            // remainder爲最後一個解元素的值,它必須大於前一個解元素的值,而且不能超出9
            if (remainder > prevVal && remainder <= 9) {
                // 添加元素值
                list.add(remainder);

                // 拷貝結果到新的隊列中
                List<Integer> one = new LinkedList<>();
                for (Integer i : list) {
                    one.add(i);
                }

                // 保存結果
                result.add(one);
                // 刪除最後一個元素,進行現場還原
                list.remove(list.size() - 1);
            }
        }
        // 不是最後一個元素
        else if (cur < k){
            for (int i = prevVal + 1; i <= 9 - (k - cur); i++) {
                // 添加元素
                list.add(i);
                // 遞歸求解
                solve(k, cur + 1, remainder - i, i, list, result);
                // 現場還原
                list.remove(list.size() - 1);

            }
        }
    }
}
相關文章
相關標籤/搜索