戻る---組み合わせた合計

合わせて合計

39.コンビネーション合計(ミディアム)

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

件名の説明:

  ターゲットを考えると、およびそれらの組み合わせの全てのコレクションは、(ターゲットのと配列要素)配列のセットを見つけるために

アイデアの分析:

  バックトラックを使用して順列の問題を探しています。

コード:

public List<List<Integer>>combinationSum(int[]candidates,int target){
    List<List<Integer>>res=new ArrayList<>();
    List<Integer>list=new ArrayList<>();
    if(candidates==null||candidates.length==0)
        return res;
    Arrays.sort(candidates); //进行排序,方便后面进行剪枝
    backtracking(candidates,0,0,res,list,target);
    return res;
}
public void backtracking(int[]candidates,int start,int sum,List<List<Integer>>res,List<Integer>list ,int target){
    if(sum==target){
        res.add(new ArrayList<>(list));
        return ;
    }
    for(int i=start;i<candidates.length;i++){
        if(sum+candidates[i]<=target){
            list.add(candidates[i]);
            backtracking(candidates,i,sum+candidates,res,list,target);//start更新为i,表示可以重复取同一个元素
            list.remove(list.size()-1);
        }else{
            break;
        }
    }
}

おすすめ

転載: www.cnblogs.com/yjxyy/p/11114075.html