string permutation with upcase and lowcase

时间:2021-08-06 03:30:32

Give a string, which only contains a-z. List all the permutation of upcase and lowcase. 
For example, str = "ab",  the output should be 
"ab", "aB", "Ab", "AB" 
for str = "abc", the output should be 
"abc", "abC", "aBc", "aBC", "Abc", "AbC", "ABc", "ABC"

[解题思路]

本题与其他permutation题目区别在于结果中每位的字符都是固定的,仅仅是大小写的区别

因而不需要循环来遍历,使字符串的每一位可以遍历任意一个值

 public class Solution {
public static void main(String[] args) {
List<String> result = new ArrayList<String>();
String tmp = "";
permutation(tmp, 0, 4, result);
System.out.println(result);
}
private static void permutation(String tmp, int depth, int len,
List<String> result) {
if (depth == len) {
result.add(tmp);
return;
} tmp += (char) ('a' + depth);
permutation(tmp, depth + 1, len, result);
tmp = tmp.substring(0, tmp.length() - 1); tmp += (char) ('A' + depth);
permutation(tmp, depth + 1, len, result);
tmp = tmp.substring(0, tmp.length() - 1); }
}