zoukankan      html  css  js  c++  java
  • leetcode : comobination sum [经典回溯]

    Given a set of candidate numbers (C) (without duplicates) 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.
    • 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) {
            List<List<Integer>> result = new ArrayList<List<Integer>>();
            if(candidates == null || candidates.length == 0) {
                return result;
            }
            List<Integer> list  = new ArrayList<Integer>();
            Arrays.sort(candidates);
            helper(result, list, candidates, target, 0);
            return result;
        }
        
        public void helper(List<List<Integer>> result, List<Integer> list, int[] nums, int remains, int position) {
            if(remains < 0) {
                return;
            }
            if(remains == 0) {
                result.add(new ArrayList<Integer>(list));
            }
            
            for(int i = position; i < nums.length; i++) {
                list.add(nums[i]);
                helper(result, list, nums, remains - nums[i],i);
                list.remove(list.size() - 1);
            }
        }
        
    }
    

      

  • 相关阅读:
    收集网址
    webstorm主题网址
    《高性能JavaScript》读书笔记
    gulp使用
    《JavaScript语言精粹》读书笔记
    浏览器检测
    《javascript高级程序设计》读书笔记
    用到的css样式(持续更新中)
    px em rem %布局
    underscorejs-indexBy学习
  • 原文地址:https://www.cnblogs.com/superzhaochao/p/6436177.html
Copyright © 2011-2022 走看看