zoukankan      html  css  js  c++  java
  • Combination Sum

    Combination Sum

    问题:

    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 (a1, a2, … , ak) must be in non-descending order. (ie, a1 ≤ a2 ≤ … ≤ ak).
    • The solution set must not contain duplicate combinations.

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

    思路:

      常见的回溯问题

    我的代码:

    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates, int target) {
            if(candidates == null || candidates.length == 0)    return rst;
            List<Integer> list = new ArrayList<Integer>();
            Arrays.sort(candidates);
            helper(list, candidates, target, 0, 0);
            return rst;
        }
        private List<List<Integer>> rst = new ArrayList<List<Integer>>();
        public void helper(List<Integer> list, int[] candidates, int target, int sum, int start)
        {
            if(sum > target)    return;
            if(sum == target)
            {
                if(!rst.contains(list))
                    rst.add(new ArrayList(list));
                return;
            }
            for(int i = start ; i < candidates.length; i++)
            {
                list.add(candidates[i]);
                helper(list, candidates, target, sum + candidates[i], i);
                list.remove(list.size() - 1);
            }
        }
    }
    View Code
  • 相关阅读:
    数组循环的各种方法的区别
    数组里面findIndex和indexOf的区别
    选择器的绑定
    把dialog对话框设置成组件的形式
    css font-family字体及各大主流网站对比
    记一下公司的备注怎么写
    可删
    瑞萨电子:嵌入式终端与人工智能融合改变工业格局
    linux有什么作用
    Linux有哪些特点
  • 原文地址:https://www.cnblogs.com/sunshisonghit/p/4326269.html
Copyright © 2011-2022 走看看