• 29.Combination Sum(和为sum的组合)


    Level:

      Medium

    题目描述:

    Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.

    The same repeated number may be chosen from candidates unlimited number of times.

    Note:

    • All numbers (including target) will be positive integers.
    • The solution set must not contain duplicate combinations.

    Example 1:

    Input: candidates = [2,3,6,7], target = 7,
    A solution set is:
    [
      [7],
      [2,2,3]
    ]
    

    Example 2:

    Input: candidates = [2,3,5], target = 8,
    A solution set is:
    [
      [2,2,2,2],
      [2,3,3],
      [3,5]
    ]
    

    思路分析:

    ​ 先对数组进行排序,方便后面递归回溯的过程中进行剪枝。然后设置一个变量sum,记录当前序列的数字和,如果sum的值等于target那么当前序列就是结果的一种,我们利用回溯的思想,找出所有满足要求得解。

    代码:

    public class Solution{
        List<List<Integer>>res=new ArrayList<>();
        public List<List<Integer>>combinationSum(int []candidates,int target){
            if(candidates==null||candidates.length==0)
                return res;
            Arrays.sort(candidates);//排序,方便后面剪枝
            find(candidates,0,0,target,new ArrayList<>());
            return res;
        }
        public void find(int[]candidates,int start,int sum,int target,ArrayList<Integer>list){
            if(sum==target){
                res.add(new ArrayList<Integer>(list));
                return;
            }
            for(int i=start;i<candidates.length;i++){
                if(sum+candidates[i]<=target){
                    list.add(candidates[i]);
                   find(candidates,i,sum+candidates[i],target,list);
                    list.remove(Integer.valueOf(candidates[i]));
                }else{
                    break; //剪枝
                }
            }
        }
    }
    
  • 相关阅读:
    ReactNative手势解锁(react-native-ok-gesture-password)
    Android通过DeepLink方式跳转其他App传递参数
    Android中注解的使用
    Windows平台下Flutter安装,配置,初运行。
    Android中MD5加密
    Android中WebView使用全解
    关于windows系统服务的操作
    java:String类型转换
    webservice服务器部署
    webservice生成客户端
  • 原文地址:https://www.cnblogs.com/yjxyy/p/10797665.html
Copyright © 2020-2023  润新知