• 784. Letter Case Permutation


    问题:

    给定一个由字母和数字组成的字符串。

    任意字母可以变换大小写,以组成新的字符串。

    求给定字符串能够组成字符串的所有可能。

    Example 1:
    Input: S = "a1b2"
    Output: ["a1b2","a1B2","A1b2","A1B2"]
    
    Example 2:
    Input: S = "3z4"
    Output: ["3z4","3Z4"]
    
    Example 3:
    Input: S = "12345"
    Output: ["12345"]
    
    Example 4:
    Input: S = "0"
    Output: ["0"]
     
    Constraints:
    S will be a string with length between 1 and 12.
    S will consist only of letters or digits.
    

      

    解法:Backtracking(回溯算法)

    • 状态:当前pos为止,构成的新字符串s[0~pos]
    • 选择:当前pos上的字符:
      • 数字:他自己
      • 字母:他自己+他的大小写转换
    • 递归退出条件:pos==字符串长度

    代码参考:

     1 class Solution {
     2 public:
     3     void backtrack(vector<string>& res, string& path, int pos) {
     4         if(pos==path.length()) {
     5             res.push_back(path);
     6             return;
     7         }
     8         backtrack(res, path, pos+1);
     9         int diff = 'A'-'a';
    10         if(path[pos]>='a' && path[pos]<='z') {
    11             path[pos]+=diff;
    12             backtrack(res, path, pos+1);
    13             path[pos]-=diff;
    14         } else if(path[pos]>='A' && path[pos]<='Z') {
    15             path[pos]-=diff;
    16             backtrack(res, path, pos+1);
    17             path[pos]+=diff;
    18         }
    19         return;
    20     }
    21     vector<string> letterCasePermutation(string S) {
    22         vector<string> res;
    23         backtrack(res, S, 0);
    24         return res;
    25     }
    26 };
  • 相关阅读:
    Item 16: 让const成员函数做到线程安全
    学习张鑫旭大神元素抛物线运动插件
    js根据浏览器对css3移动的支持,选择元素移动方式
    如何在图片加载完成前获取到图片宽高
    JavaScript和SVG实现点击连线
    多层级叠加问题
    闭包应用
    展示触摸屏网页打包成桌面应用(nw.js)
    获取鼠标坐标
    常用文档
  • 原文地址:https://www.cnblogs.com/habibah-chang/p/14334746.html
Copyright © 2020-2023  润新知