• Java [Leetcode 39]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]

    解题思路:

    首先将数组排序,然后应用回溯和贪心的算法,首先从最小的数开始,尽可能的将该数字放入List中,如果加入的数目太多导致下面没有数字可以使综合等于target则将之前加入的数字弹出,换进下一个数字,如此反复。

    代码如下:

    public class Solution {
        public List<List<Integer>> combinationSum(int[] candidates,
    			int target) {
    		Arrays.sort(candidates);
    		List<List<Integer>> result = new ArrayList<List<Integer>>();
    		getResult(result, new ArrayList<Integer>(), candidates, target, 0);
    		return result;
    	}
    
    	public void getResult(List<List<Integer>> result,
    			List<Integer> current, int[] candiates, int target, int start) {
    		if (target > 0) {
    			for (int i = start; i < candiates.length && target >= candiates[i]; i++) {
    				current.add(candiates[i]);
    				getResult(result, current, candiates, target - candiates[i], i);
    				current.remove(current.size() - 1);
    			}
    		} else if (target == 0) {
    			result.add(new ArrayList<Integer>(current));
    		}
    	}
    }
    

      

  • 相关阅读:
    超详细动画彻底掌握深度优先,广度优先遍历!
    拜托,别再问我什么是 B+ 树了
    高性能短链设计
    Gradle build 太慢,可能是你使用的姿势不对
    看完这些,你也能成技术专家
    x58平台 服务器电源配置 tdp
    系统掉盘,机械硬盘掉盘,固态掉盘
    centos7 修改ip和dns
    centos 修改hostname
    TCP三次握手和四次挥手过程
  • 原文地址:https://www.cnblogs.com/zihaowang/p/5020537.html
Copyright © 2020-2023  润新知