组合
给定两个整数 n 和 k,返回范围 [1, n] 中所有可能的 k 个数的组合。
你可以按 任何顺序 返回答案。
输入: n = 4, k = 2
输出:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
输入: n = 1, k = 1
输出: [[1]]
提示:
1 <= n <= 201 <= k <= n
class Solution {
public List<List<Integer>> combine(int n, int k) {
List<List<Integer>> resultList = new ArrayList();
Stack<Integer> stack = new Stack<Integer>();
back(n,k, 1, stack, resultList);
return resultList;
}
private void back(int n, int k , int startIdx, Stack stack, List<List<Integer>> resultList){
if(stack.size() == k){
resultList.add(new ArrayList(stack));
return;
}
for (int i= startIdx; i<=n; i++){
stack.push(i);
back(n, k, i+1, stack, resultList);
stack.pop();
}
}
}
全排列
给定一个不含重复数字的数组 nums ,返回其 所有可能的全排列 。你可以 按任意顺序 返回答案。
输入: nums = [1,2,3]
输出: [[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
输入: nums = [0,1]
输出: [[0,1],[1,0]]
输入: nums = [1]
输出: [[1]]
提示:
1 <= nums.length <= 6-10 <= nums[i] <= 10nums中的所有整数 互不相同 leetcode-cn.com/problems/pe…
class Solution {
public List<List<Integer>> permute(int[] nums) {
List<List<Integer>> resultList = new ArrayList();
Stack<Integer> stack = new Stack<Integer>();
int[] visited = new int[nums.length];
back(nums, stack, resultList, visited);
return resultList;
}
private void back(int[] nums , Stack stack, List<List<Integer>> resultList, int[] visited){
if(stack.size() == nums.length){
resultList.add(new ArrayList(stack));
return;
}
for (int i= 0; i<nums.length; i++){
if (visited[i] == 1) continue;
stack.push(nums[i]);
visited[i]= 1;
back(nums, stack, resultList, visited);
visited[i] =0;
stack.pop();
}
}
}
字母大小写全排列
给定一个字符串S,通过将字符串S中的每个字母转变大小写,我们可以获得一个新的字符串。返回所有可能得到的字符串集合。
输入:S = "a1b2"
输出:["a1b2", "a1B2", "A1b2", "A1B2"]
输入:S = "3z4"
输出:["3z4", "3Z4"]
输入:S = "12345"
输出:["12345"]
提示:
S的长度不超过12。S仅由数字和字母组成。
class Solution {
List<String> res = new ArrayList<>();
public List<String> letterCasePermutation(String s) {
res.add(s);
backTrack(s.toCharArray(),0);
return res;
}
private void backTrack(char[] chars, int start){
for(int i = start; i < chars.length;i++){
if(chars[i] > '9'){
chars[i] ^= 32;
res.add(String.valueOf(chars));
backTrack(chars,i+1);
chars[i] ^= 32;
}
}
}
}