zoukankan      html  css  js  c++  java
  • 乘风破浪:LeetCode真题_039_Combination Sum

    乘风破浪:LeetCode真题_039_Combination Sum

    一、前言

        这一道题又是集合上面的问题,可以重复使用数字,来求得几个数之和等于目标。

    二、Combination Sum

    2.1 问题

    2.2 分析与解决

        我们可以先将大于该数字的元素去除掉,之后取出一个元素,做减法,将得到的结果再放到集合中比较,直至最后减得结果为零则成功,为负数则失败回退。因此我们可以使用递归、堆栈、队列等来解决。

    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;
        }
        
        private void getResult(List<List<Integer>> result, List<Integer> cur, int candidates[], int target, int start){
        	if(target > 0){
        		for(int i = start; i < candidates.length && target >= candidates[i]; i++){
        			cur.add(candidates[i]);
        			getResult(result, cur, candidates, target - candidates[i], i);
        			cur.remove(cur.size() - 1);
        		}//for
        	}//if
        	else if(target == 0 ){
        		result.add(new ArrayList<Integer>(cur));
        	}//else if
        }
    }
    

    三、总结

        遇到这种问题,首先想到递归,动态规划等方面的知识,然后不断地练习和尝试。

  • 相关阅读:
    常用网络操作命令
    C语言中的位域[转]
    状态机——一种强大的思想利器
    9030PCI CAN驱动开发点滴
    驱动开发中应该注意的事项
    java 从网络Url中下载文件
    windows pyspider 爬虫安装
    java list去重
    Java 文件分块及合并
    工程部署到linux
  • 原文地址:https://www.cnblogs.com/zyrblog/p/10224760.html
Copyright © 2011-2022 走看看