给一个字符串abcd 然后再两两组合 三三组合

qq_25451779 2015-01-19 09:14:50
如: ab ac ad bc bd cb abc abd bcd bca

从左往右 和从右往左 都需要
求大神给段代码最好再详解,


明天面试
...全文
425 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
ssson 2018-12-27
  • 打赏
  • 举报
回复
public class Abcd { private static final String[] str = { "a", "b", "c", "d" }; private static String res = ""; int len = str.length; public static void main(String[] args) { t2(); t3(); } private static void t2() { for (int i = 0; i < str.length; i++) { res = str[i]; for (int j = 0; j < str.length; j++) { System.out.println(res + str[j]); } } } private static void t3() { for (int i = 0; i < str.length; i++) { res = str[i]; for (int j = 0; j < str.length; j++) { // System.out.println(res + str[j]); for (int k = 0; k < str.length; k++) { System.out.println(res + str[j] + str[k]); } } } } }
雨季余静 2018-12-27
  • 打赏
  • 举报
回复
   List<String> result = new ArrayList<>();
@Test
public void test() {
String[] target = new String[]{"a", "b", "c", "d"};
for (int i = 1; i <= target.length; i++)
calc(i, "", target);
System.out.println(Arrays.toString(result.toArray()));
}

//递归
public void calc(int length, String p, String... target) {
for (String item : target)
if (!p.contains(item) && (!((length == 1) && result.add(p + item))))
calc(length - 1, p + item, target);
}
普凡 2015-01-20
  • 打赏
  • 举报
回复

public static void main(String[] args) {
    
        String arr[] = { "a", "b", "c", "d" };
        int all = 4;
        for (int i = 0; i < 1 << all; i++) {
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < all; j++) {
                if ((i & (1 << j)) != 0) {
                    sb.append(arr[j]);
                }
            }
            System.out.println(sb);
        }
    }


62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧