JAVA-----------Easy Version To underStand!!!!!!Similar to Combination Sum&&Combination Sum I


  • 0
    H
    	public static void DFS(int k, int n, List<List<Integer>> result, List<Integer> sequence, int startNumber, int sum,
    		int num) {
    	if (sum > n || num > k)
    		return;
    	else if (sum == n && num == k)
    		result.add(new ArrayList<Integer>(sequence));
    	else if (sum < n && num < k) {
    		for (int i = startNumber; i <= 9; i++) {
    			sum += i;
    			sequence.add(i);
    			num++;
    			DFS(k, n, result, sequence, i + 1, sum, num);
    			sum -= i;
    			sequence.remove(sequence.size() - 1);
    			num--;
    		}
    	}
    }
    
    public static List<List<Integer>> combinationSum3(int k, int n) {
    	if (k <= 0)
    		return new ArrayList<List<Integer>>();
    	List<List<Integer>> result = new ArrayList<List<Integer>>();
    	List<Integer> sequence = new ArrayList<Integer>();
    	DFS(k, n, result, sequence, 1, 0, 0);
    	return result;
    }

Log in to reply
 

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