Simple Java Solution, same idea with 320 Generalized Abbreviation


  • 0
    F

    Here is my solution, same idea with 320. Generalized Abbreviation. For each number, we can decide use it or not. If we use it, the counter will plus one and the sum will add it. If not, the counter and sum will not changed.

    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            List<List<Integer>> list = new ArrayList<>();
            helper(list,1,0,k,n,new ArrayList<Integer>(),0);
            return list;
        }
        public void helper(List<List<Integer>> list,int num, int count, int k,int target, List<Integer> list2, int sum){
            if(count == k && sum == target){
                List<Integer> li = new ArrayList<Integer>(list2);
                list.add(li);
            }
            else if(num <=9){
                list2.add(num);
                helper(list,num+1,count+1,k,target,list2,sum+num);
                list2.remove(list2.size()-1);
                helper(list,num+1,count,k,target,list2,sum);
            }
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.