[LintCode]k Sum

来源:互联网 发布:epub360 知乎 编辑:程序博客网 时间:2024/05/17 01:53

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;    }}


0 0
原创粉丝点击