combinations Sum

By   Tewodros   Date Posted: Oct. 9, 2023  Hits: 329   Category:  Algorithm   Total Comment: 0             A+ A-


side

Given an array of distinct integers candidates and a target integer target, return a list of all combinations of candidates where the chosen numbers sum to target. You may return the combinations in any order.

The same number may be chosen from candidates an unlimited number of times

Example 1:

Input:

 candidates = [2,3,6,7], target = 7

Output:

 [[2,2,3],[7]]

 

Solution:

public class Solution {

    public IList<IList<int>> CombinationSum(int[] candidates, int target) {

         List<IList<int>> ans = new List<IList<int>>();

         BackTrack(candidates,0, target,new List<int>(), ans);

         return ans;

    }

    

       public void BackTrack(int[] cand, int start,int target,List<int> list, List<IList<int>> result)

            {

                if (target < 0)

                    return;

                if (target == 0)

                    result.Add(new List<int>(list));


 

                for (int i = start; i < cand.Length; i++)

                {

                    list.Add(cand[i]);

                    BackTrack(cand, i, target - cand[i], list, result);

                    list.RemoveAt(list.Count-1);

                }

            }

}


Tags



Back to Top



Related Blogs






Please fill all fields that are required and click Add Comment button.

Name:*
Email:*
Comment:*
(Only 2000 char allowed)


Security Code:* yecbvz

Back to Top