美文网首页
LeetCode每日一题:combination sum i

LeetCode每日一题:combination sum i

作者: yoshino | 来源:发表于2017-06-26 16:27 被阅读29次

    问题描述

    Given a set of candidate numbers ( C ) and a target number ( T ), find all unique combinations in C where the candidate numbers sums to T .
    The same repeated number may be chosen from C unlimited number of times.
    Note:
    All numbers (including target) will be positive integers.
    Elements in a combination (a 1, a 2, … , a k) must be in non-descending order. (ie, a 1 ≤ a 2 ≤ … ≤ a k).
    The solution set must not contain duplicate combinations.

    For example, given candidate set2,3,6,7and target7,
    A solution set is:
    [7]
    [2, 2, 3]

    问题分析

    这题考察的回溯法点的应用,由于可以存在相同的数,所以回溯还是从i开始,具体实现看代码就行了。基本上像这种列举解的算法都是用回溯+递归进行的。没有什么额外的难度。

    代码实现

    public ArrayList<ArrayList<Integer>> combinationSum(int[] candidates, int target) {
            Arrays.sort(candidates);
            ArrayList<ArrayList<Integer>> result = new ArrayList<>();
            ArrayList<Integer> list = new ArrayList<>();
            backTrackingSum(candidates, 0, target, list, result);
            return result;
        }
    
        private void backTrackingSum(int[] cadidates, int start, int target, ArrayList<Integer> list,
                                     ArrayList<ArrayList<Integer>> result) {
            if (target == 0) {
                result.add(new ArrayList<Integer>(list));
                return;
            } else {
                for (int i = start; i < cadidates.length && cadidates[i] <= target; i++) {
                    list.add(cadidates[i]);
                    backTrackingSum(cadidates, i, target - cadidates[i], list, result);
                    list.remove(list.size() - 1);
                }
            }
        }
    

    相关文章

      网友评论

          本文标题:LeetCode每日一题:combination sum i

          本文链接:https://www.haomeiwen.com/subject/bzdjcxtx.html