Given a set of candidate numbers (candidates) (without duplicates) and a target number (target), find all unique combinations in candidates where the candidate numbers sums to target.
The same repeated number may be chosen from candidates unlimited number of times.
Note:
All numbers (including target) will be positive integers. The solution set must not contain duplicate combinations.
1
Example 1:
Input: candidates = [2,3,6,7], target = 7,
A solution set is:
[
[7],
[2,2,3]
]
Example 2:
Input: candidates = [2,3,5], target = 8,
A solution set is:
[
[2,2,2,2],
[2,3,3],
[3,5]
]
classSolution{ public List<List<Integer>> combinationSum(int[] candidates, int target) { List<List<Integer>> results = new ArrayList<>(); if (candidates == null || candidates.length == 0) { return results; } Arrays.sort(candidates); combinations(results, new ArrayList<>(), candidates, target, 0); return results; }
privatevoidcombinations(List<List<Integer>> results, List<Integer> list, int[] candidates, int target, int index){ int s = sum(list); if (s == target) { results.add(copyOf(list)); return; } if (s > target) { return; }
for (int i = index; i < candidates.length; i++) { list.add(candidates[i]); combinations(results, list, candidates, target, i); list.remove(list.size() - 1); } }
privateintsum(List<Integer> list){ if (list == null) { return0; } int sum = 0; for (Integer i : list) { sum += i; } return sum; }
The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.
Given an integer n, return all distinct solutions to the n-queens puzzle.
Each solution contains a distinct board configuration of the n-queens’ placement, where ‘Q’ and ‘.’ both indicate a queen and an empty space respectively.
Example:
1
Input: 4
Output: [
[".Q..", // Solution 1
"...Q",
"Q...",
"..Q."],
["..Q.", // Solution 2
"Q...",
"...Q",
".Q.."]
]
Explanation: There exist two distinct solutions to the 4-queens puzzle as shown above.