[LintCode]k Sum

http://www.lintcode.com/en/problem/k-sum/

求k個數和爲target的總解數




cache裏面需要包三層!比較複雜!想清楚當前解需要多少狀態決定!k & target & index都需要!!!

當前位置兩種選擇,取或者不取

public class Solution {
    /**
     * @param A: an integer array.
     * @param k: a positive integer (k <= length(A))
     * @param target: a integer
     * @return an integer
     */
    public int kSum(int A[], int k, int target) {
        // write your code here
        return dfs(A, k, target, 0);
    }
    HashMap<Integer, HashMap<Integer, HashMap<Integer, Integer>>> map = new HashMap();
    private int dfs(int[] nums, int k, int target, int index) {
        if (map.containsKey(index) && map.get(index).containsKey(target) && map.get(index).get(target).containsKey(k)) {
            return map.get(index).get(target).get(k);
        }
        if (target <= 0) {
            return (target == 0 && k == 0) ? 1 : 0;
        }
        if (k <= 0) {
            return 0;
        }
        if (index == nums.length) {
            return 0;
        }
        int res = 0;
        // 當前位置取或者不取
        res += dfs(nums, k - 1, target - nums[index], index + 1);
        res += dfs(nums, k, target, index + 1);
        HashMap<Integer, HashMap<Integer, Integer>> tragetMap = null;
        if (map.containsKey(index)) {
            tragetMap = map.get(index);
        } else {
            tragetMap = new HashMap();
        }
        HashMap<Integer, Integer> kMap = null;
        if (tragetMap.containsKey(target)) {
            kMap = tragetMap.get(target);
        } else {
            kMap = new HashMap();
        }
        kMap.put(k, res);
        tragetMap.put(target, kMap);
        map.put(index, tragetMap);
        return res;
    }
}


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