Beats 96.33% of all JAVA solutions. Easy to understand.


  • 0
    B
    public class Solution {
        public List<List<Integer>> combinationSum3(int k, int n) {
            if (k>9 ||k<=0){
                return null;
            }
            return (List)helper(k,n,1);
        }
        private List<LinkedList<Integer>> helper(int k,int target,int start){
            List<LinkedList<Integer>> ans=new LinkedList<>();
            if (k==1 && target>=start && target<=9){
                ans.add(new LinkedList<Integer>(){{add(target);}});
            }
            else if(k<=1){
                return ans;
            }
            else{
                for (int i=start;i<=9;i++){
                    if (target>=i) {
                        List<LinkedList<Integer>> temp = helper(k - 1, target - i,i+1); 
                        //for example,
                        //if i==1,then target==8,temp=[2,6],[3,5]
                        //if i==2,then target==6,temp=[6]
                        for (LinkedList<Integer> ll : temp) {
                            ll.addFirst(i);//for example, add '1' to [2,6]
                            ans.add(ll);
                        }
                    }
                    else break;
                }
            }
            return ans;
        }
    }

Log in to reply
 

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