[LintCode]k Sum II

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

找出所有和爲target且長度爲k的子數組





dfs,當前位置可以選也可以不選

public class Solution {
    /**
     * @param A: an integer array.
     * @param k: a positive integer (k <= length(A))
     * @param target: a integer
     * @return a list of lists of integer 
     */ 
    public ArrayList<ArrayList<Integer>> kSumII(int[] A, int k, int target) {
        // write your code here
        ArrayList<ArrayList<Integer>> res = new ArrayList();
        dfs(res, A, k, target, 0, new ArrayList());
        return res;
    }
    private void dfs(ArrayList<ArrayList<Integer>> res, int[] nums, int k, int target, int index, ArrayList<Integer> list) {
        if (target == 0 && k == 0) {
            res.add(new ArrayList(list));
            return;
        }
        if (k < 0 || index >= nums.length || target < 0) {
            return;
        }
        dfs(res, nums, k, target, index + 1, list);
        list.add(nums[index]);
        dfs(res, nums, k - 1, target - nums[index], index + 1, list);
        list.remove(list.size() - 1);
    }
}


發佈了363 篇原創文章 · 獲贊 1 · 訪問量 9萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章