java solution


  • 0
    P

    More complex than I thought...Σ(  ̄□ ̄||) but this algorithm can be used in many questions, I think. (ノ≧∇≦)ノ
    First we get all sorts of combinations from 1 to 9.
    Then everything is ok.(╯°口°)╯(┴—┴

    public class Solution {
        int[] nums = {1,2,3,4,5,6,7,8,9};
        List<List<Integer>> list = new ArrayList<>();
        List<List<Integer>> result = new ArrayList<>();
        public List<List<Integer>> combinationSum3(int k, int n) {
            if(n == 0)
            {
                return list;
            }
            for(int i = 1;i<=nums.length;i++)
            {
                generate(nums,i,list);
            }
            int sum = 0;
            for(int j = 1;j<list.size();j++)
            {
                for(int v = 0;v<list.get(j).size();v++)
                {
                    sum = sum + list.get(j).get(v);
                }
                if(sum == n&&list.get(j).size() == k)
                {
                    result.add(list.get(j));
                }
                sum = 0;
            }
            return result;
        }
        public void generate(int[] nums, int count,List<List<Integer>> list)
        {
            List<Integer> res = new ArrayList<>();
            generating(nums,count,0,res,list);
            return;
        }
        public void generating(int[] nums,int count,int start,List<Integer> res,List<List<Integer>> list)
        {
            if(count == 0)
            {
                list.add(new ArrayList<>(res));
            }
            for(int i = start;i<nums.length;i++)
            {
                res.add(nums[i]);
                generating(nums,count-1,i+1,res,list);
                res.remove(res.size()-1);
            }
        }
    }

Log in to reply
 

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